How do you add CSS with Javascript?

前端 未结 14 2752
旧时难觅i
旧时难觅i 2020-11-22 17:18

How do you add CSS rules (eg strong { color: red }) by use of Javascript?

14条回答
  •  Happy的楠姐
    2020-11-22 17:56

    This is my solution to add a css rule at the end of the last style sheet list:

    var css = new function()
    {
        function addStyleSheet()
        {
            let head = document.head;
            let style = document.createElement("style");
    
            head.appendChild(style);
        }
    
        this.insert = function(rule)
        {
            if(document.styleSheets.length == 0) { addStyleSheet(); }
    
            let sheet = document.styleSheets[document.styleSheets.length - 1];
            let rules = sheet.rules;
    
            sheet.insertRule(rule, rules.length);
        }
    }
    
    css.insert("body { background-color: red }");
    

提交回复
热议问题