【问题标题】:Modifying the innerHTML of a <style> element in IE8在 IE8 中修改 <style> 元素的 innerHTML
【发布时间】:2011-10-01 16:35:50
【问题描述】:

我正在创建一个样式元素,我需要在其中添加一些 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);

但这也因“意外调用方法或属性访问”而失败。 我正在寻找解决方法或修复方法。

【问题讨论】:

    标签: coding-style internet-explorer-8 innerhtml


    【解决方案1】:

    使用.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";
    

    【讨论】:

      【解决方案2】:

      尝试使用styleElement.innerText

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-13
        • 1970-01-01
        • 2021-09-09
        • 2011-08-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多