开发者

Javascript Jquery Add StyleSheet IE

There is my code source :

            nodeCss = $('<link rel="stylesheet" href="about:blank" type="text/css" 

media="all" />');
                nodeCss.attr('href',css_file);
                $("head").append(nodeCss);

I have two problems on IE :

  • The first is stylesheet is ignored for the first time : my page allow me to reload a code, and when i do that, the stylesheet isn't more ignored. It's possible that stylesheet must be loaded before insert new Elements who are targetted by styleSheet.

  • The second problem, so the first can be "hacked" (because only on IE), it's the background "url(...)" in my dynamic stylesheet are never loaded in dynamic loading css file by javascript. the same action width a normal stylesheet on HTML results a background ok. One more, it's only IE : Chrome and Firefox does the w开发者_开发技巧ork very good.

Sorry for my language, i speak a little english, be comprehensible.

Thanks a lot.


Try using document.createStylesheet for IE browsers. MSDN has an article on how to use this method.

A potential cross browser solution:

(document.createStyleSheet) ? document.createStyleSheet(css_file) : $('<link rel="stylesheet" type="text/css" href="' + css_file + '" />').appendTo('head')


I won't answer directly to your question, because there are much more reliable and simpler ways how to achieve the desired effect.

If you want to dynamically load a CSS file appended to document using <link> element, just add it to your markup and set it the disabled attribute initially: <link rel=stylesheet href=style.css disabled>. All you have to do in JS/DOM is to set its DOM property disabled to false (boolean value). In jQuery, prop() method should be used to do this.

If your css_file variable can take more different values depending on some other code, the recommended solution is to change the class of <html> element. Then, you can easily use selectors like .state1 #selector and .state2 #selector to express different states in the HTML document.


Adding a stylesheet dynamically with jQuery gives me a lot of issues in older versions of IE. Here's what I've ended up using that works cross-browser:

// Prevent Firefox security error
document.getElementsByTagName('head')[0].appendChild(document.createElement('style'));

// Get last style sheet so that the rules we add will take precedence
var sheet = document.styleSheets[document.styleSheets.length-1]; 


// Internet Explorer method
if(sheet.addRule)
{

    // FORMAT:
    // sheet.addRule('selector','rule: xxx');
    // sheet.addRule('selector','rule: xxx');

    sheet.addRule('a:hover','color: yellow');
    sheet.addRule('a:hover','text-decoration: none');

}

// All other browsers
if(sheet.insertRule)
{

    // FORMAT: sheet.insertRule('selector { rule: xxx; rule: xxx; rule: xxx; }');
    sheet.insertRule('a:hover { color: yellow; text-decoration: none; }', sheet.cssRules.length);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜