How to dynamically create CSS class in JavaScript and apply?

后端 未结 15 1226
长情又很酷
长情又很酷 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:37

    Here is my modular solution:

    var final_style = document.createElement('style');
    final_style.type = 'text/css';
    
    function addNewStyle(selector, style){
      final_style.innerHTML += selector + '{ ' + style + ' } \n';
    };
    
    function submitNewStyle(){
      document.getElementsByTagName('head')[0].appendChild(final_style);
    
      final_style = document.createElement('style');
      final_style.type = 'text/css';
    };
    
    function submitNewStyleWithMedia(mediaSelector){
      final_style.innerHTML = '@media(' + mediaSelector + '){\n' + final_style.innerHTML + '\n};';
        submitNewStyle();
    };
    

    You basically anywhere in your code do:
    addNewStyle('body', 'color: ' + color1); , where color1 is defined variable.

    When you want to "post" the current CSS file you simply do submitNewStyle(),
    and then you can still add more CSS later.

    If you want to add it with "media queries", you have the option.
    After "addingNewStyles" you simply use submitNewStyleWithMedia('min-width: 1280px');.


    It was pretty useful for my use-case, as I was changing CSS of public (not mine) website according to current time. I submit one CSS file before using "active" scripts, and the rest afterwards (makes the site look kinda-like it should before accessing elements through querySelector).

提交回复
热议问题