How to dynamically create CSS class in JavaScript and apply?

后端 未结 15 1229
长情又很酷
长情又很酷 2020-11-22 02:57

I need to create a CSS stylesheet class dynamically in JavaScript and assign it to some HTML elements like - div, table, span, tr, etc and to some controls like asp:Textbox,

15条回答
  •  一个人的身影
    2020-11-22 03:35

    An interesting project which could help you out in your task is JSS.

    JSS is a better abstraction over CSS. It uses JavaScript as a language to describe styles in a declarative and maintainable way. It is a high performance JS to CSS compiler which works at runtime in the browsers and server-side.

    JSS library allows you to inject in the DOM/head section using the .attach() function.

    Repl online version for evaluation.

    Further information on JSS.

    An example:

    // Use plugins.
    jss.use(camelCase())
    
    // Create your style.
    const style = {
      myButton: {
        color: 'green'
      }
    }
    
    // Compile styles, apply plugins.
    const sheet = jss.createStyleSheet(style)
    
    // If you want to render on the client, insert it into DOM.
    sheet.attach()
    

提交回复
热议问题