How to dynamically create CSS class in JavaScript and apply?

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

    Short answer, this is compatible "on all browsers" (specifically, IE8/7):

    function createClass(name,rules){
        var style = document.createElement('style');
        style.type = 'text/css';
        document.getElementsByTagName('head')[0].appendChild(style);
        if(!(style.sheet||{}).insertRule) 
            (style.styleSheet || style.sheet).addRule(name, rules);
        else
            style.sheet.insertRule(name+"{"+rules+"}",0);
    }
    createClass('.whatever',"background-color: green;");
    

    And this final bit applies the class to an element:

    function applyClass(name,element,doRemove){
        if(typeof element.valueOf() == "string"){
            element = document.getElementById(element);
        }
        if(!element) return;
        if(doRemove){
            element.className = element.className.replace(new RegExp("\\b" + name + "\\b","g"));
        }else{      
            element.className = element.className + " " + name;
        }
    }
    

    Here's a little test page as well: https://gist.github.com/shadybones/9816763

    The key little bit is the fact that style elements have a "styleSheet"/"sheet" property which you can use to to add/remove rules on.

提交回复
热议问题