How to dynamically change the style tag using JavaScript?

前端 未结 9 2173
走了就别回头了
走了就别回头了 2021-01-01 21:50

I want to change the style tag after generating contents. How can I add style to the style tag? I tried using:

document.getElementById(\'style\').appendChil         


        
9条回答
  •  忘掉有多难
    2021-01-01 22:24

    If you want to append rules to an existing style sheet, the official way to do is with the insertRule methods. It will probably be alot easier on the browser then just appending text. Also if you do it like below, if there is a particular css rule is not valid syntax, it will skip it, thus protecting the integrity of your document.

    Uses jQuery just for string timming, probably not needed anyway.

    You have to give it the ID of the style tag.

    function AddMoreStyles(code, styleTagId) {
    
        var sheet = document.getElementById('#' + styleTagId);
    
        let lines = code.replace(/[\r\n\t]/gm, ' ').split(/}/);
        if (!sheet) {
            return;
        }
        sheet = sheet.styleSheet || sheet.sheet || sheet;
        lines.forEach(function (str) {
            str = $.trim(str) + '}';
            let m = str.match(/(.+?)\{(.*?)}/), m1, m2;
            if (m) {
                m1 = $.trim(m[1]);
                m2 = $.trim(m[2]);
                try {
                    if (sheet.insertRule) sheet.insertRule(m1 + '{' + m2 + '}', sheet.cssRules.length);
                    else sheet.addRule(m1, m2);
                } catch (e) {
                    console.log("!ERROR in css rule: " + e.message);
                }
            }
        });
    };
    

提交回复
热议问题