动态添加样式表时IE 8和7的错误

Oma*_*bid 6 internet-explorer coding-style

我有以下代码

var style = document.createElement('style');
style.setAttribute("type", "text/css");
if (style.textContent) { // FF, Safari
    style.textContent = this.arg.css;
} else {
    style.innerHTML = this.arg.css;// FF, IE
}
document.getElementsByTagName('head')[0].appendChild(style);
Run Code Online (Sandbox Code Playgroud)

这适用于所有浏览器(也是IE 9),但对于IE7和IE8,我收到以下错误

SCRIPT600:未知的运行时错误

错误指向该行

    style.innerHTML = this.arg.css;// FF, IE
Run Code Online (Sandbox Code Playgroud)

怎么了?

Ale*_*x K 10

你可以尝试这种方式

var style = document.createElement('style');
var text = this.arg.css;
style.setAttribute("type", "text/css");
if (style.styleSheet) {   // for IE
    style.styleSheet.cssText = text;
} else {                // others
    var textnode = document.createTextNode(text);
    style.appendChild(textnode);
}
var h = document.getElementsByTagName('head')[0];
h.appendChild(style);
Run Code Online (Sandbox Code Playgroud)

  • 显然,IE对它允许的样式表数量有限制,如果你达到了这个限制,这种行为就会触发.我很确定这就是我遇到的情况. (3认同)