How do you add CSS with Javascript?

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

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

相关标签:
14条回答
  • 2020-11-22 18:08

    if you know at least one <style> tag exist in page , use this function :

    CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};
    

    usage :

    CSS("div{background:#00F}");
    
    0 讨论(0)
  • 2020-11-22 18:10

    Here's my general-purpose function which parametrizes the CSS selector and rules, and optionally takes in a css filename (case-sensitive) if you wish to add to a particular sheet instead (otherwise, if you don't provide a CSS filename, it will create a new style element and append it to the existing head. It will make at most one new style element and re-use it on future function calls). Works with FF, Chrome, and IE9+ (maybe earlier too, untested).

    function addCssRules(selector, rules, /*Optional*/ sheetName) {
        // We want the last sheet so that rules are not overridden.
        var styleSheet = document.styleSheets[document.styleSheets.length - 1];
        if (sheetName) {
            for (var i in document.styleSheets) {
                if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(sheetName) > -1) {
                    styleSheet = document.styleSheets[i];
                    break;
                }
            }
        }
        if (typeof styleSheet === 'undefined' || styleSheet === null) {
            var styleElement = document.createElement("style");
            styleElement.type = "text/css";
            document.head.appendChild(styleElement);
            styleSheet = styleElement.sheet;
        }
    
        if (styleSheet) {
            if (styleSheet.insertRule)
                styleSheet.insertRule(selector + ' {' + rules + '}', styleSheet.cssRules.length);
            else if (styleSheet.addRule)
                styleSheet.addRule(selector, rules);
        }
    }
    
    0 讨论(0)
提交回复
热议问题