【问题标题】:getting an error in IE8 when dynamically creating style element and appending to it [duplicate]动态创建样式元素并附加到它时在 IE8 中出现错误 [重复]
【发布时间】:2014-11-10 15:41:39
【问题描述】:

当我创建样式元素并尝试将代码附加到它时,下面的代码会引发错误Error: Unexpected call to method or property access:

//This is OK
var styleElement = document.createElement("style");

//This is OK
styleElement.type = "text/css";

//THIS THROWS THE ERROR
styleElement.appendChild(document.createTextNode("a { color: red; }"));

我做错了什么?

【问题讨论】:

标签: javascript html css internet-explorer-8


【解决方案1】:

您必须在旧版本的 IE (6-8) 中这样做:

styleElement.styleSheet.cssText = "a { color: red; }";

你可以这样做来支持多个浏览器/版本:

var style = "a { color: red; }";

if(styleElement.styleSheet) styleElement.styleSheet.cssText = style;
else styleElement.appendChild(document.createTextNode(style));

【讨论】:

  • 不确定我是否正确,但我认为设置 .styleSheet.cssText 必须在 元素附加到文档之后完成(来自我在其他 SO问题)。无论哪种方式,这都是正确的答案
  • @Ian 它在 IE8 中工作,无需将其添加到文档/标题中。我在后面附加它。
  • 帮助解决可能发现的问题:是的,先添加,然后添加文本!!我在我正在开发的应用程序中发现了这一点。在追加之前先设置 css 文本会导致奇怪的行为,并可能从规则中删除限定符。这显示了我在兼容 IE8 模式下运行 IE11。在附加到头部之前设置文本会导致与背景属性关联的所有 !important 修饰符被删除。问题是很难调试和找出这么简单的东西。
猜你喜欢
  • 2018-07-20
  • 1970-01-01
  • 2015-02-05
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多