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

前端 未结 5 1336
被撕碎了的回忆
被撕碎了的回忆 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:27

    This has been tested to work on all major browsers (Chrome/Safari/FF/Opera/IE) including IE6,7+8:

    function createCSS(css, doc) {
        doc = doc || document;
        var style = doc.createElement("style");
        style.type = "text/css";
    
        if (!window.opera && 'styleSheet' in style && 'cssText' in style.styleSheet) {
            // Internet Explorer 6-8 don't support adding text nodes to 
            // styles, so use the proprietary `styleSheet.cssText` instead
            style.styleSheet.cssText = css;
        }
        else {
            // Otherwise use the standard method
            style.appendChild(doc.createTextNode(css));
        }
    
        // Note the `|| document.body` as getting the
        // head doesn't always work on e.g. Safari 1.0
        var head = doc.getElementsByTagName("head")[0] || doc.body;
    
        // Add the new style of higher priority than the last
        // ones if there's already other elements in the head
        if (head.firstChild) {
            head.insertBefore(style, head.firstChild);
        }
        else {
            head.appendChild(style);
        }
    }
    

    As that code is written, it is relative to the document being served so may need to be modified to make it relative to another path, or you could use absolute image paths in the CSS.

    EDIT: Removed all the innerHTML references in favour of using the more standard createTextNode when possible and cleaned various things up.

提交回复
热议问题