我正在创建一个样式元素,我需要将一些 CSS 放入其中。以下代码在 Chrome、Safari 和 FF 中有效,但在 IE8 中失败:
var styleElement = document.createElement("style");
styleElement.type = "text/css";
styleElement.innerHTML = "body{background:red}";
document.head.appendChild(styleElement);
在 IE8 中,代码在涉及到 innerHTML 部分时失败。我试过这样做:
var inner = document.createTextNode("body{background:red}");
styleElement.appendChild(inner);
但这也会因“对方法或属性访问的意外调用”而失败。
我正在寻找解决方法或修复方法。
最佳答案
使用 .styleSheet.cssText
注意:与修改单个元素样式相比,这在 IE8 中似乎真的很慢。
有没有更快的方法在 IE 中动态修改样式表?
这在 IE8 中很慢:
styleElement.styleSheet.cssText = "body{background:red}";
这在 IE8 中也很慢(假设要修改的样式对象是头部的第一个样式元素):
document.styleSheets[0].cssText = "body{background:red}";
这在 IE8 中很快:
document.body.style.background = "red";
关于coding-style - 在 IE8 中修改 <style> 元素的 innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6631871/