controlling css with javascript works with Mozilla & Chrome however not with IE

前端 未结 5 1373
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 17:57

Im having problems with this function applying css(using a text variable) working with Internet Explorer but it works in Firefox & Chrome.

the code:



        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 18:31

    This works fine for me on all current browsers with any type of document (which I assume you must be dealing with multiple documents, or otherwise you wouldn't have a Doc parameter):

    function add_css_style(css_rules, document) {
        document = document || self.document;
        var style = document.createElementNS("http://www.w3.org/1999/xhtml", "style");
        style.type = "text/css";
        style.appendChild(document.createTextNode(css_rules));
        document.documentElement.appendChild(style);
    }
    

    If you want to use the CSSOM instead:

    function add_css_style(css_rules, document) {
        document = document || self.document;
        var stylesheet = document.documentElement.appendChild(
            this.createElementNS("http://www.w3.org/1999/xhtml", "style")
        ).sheet;
        stylesheet.insertRule("@media all{" + rules + "}", 0);
    }
    

提交回复
热议问题