Modifying the innerHTML of a <style> element in IE8

断了今生、忘了曾经 提交于 2020-01-01 04:12:05

问题


I am creating a style element and I need to put some CSS into it. The below code works in Chrome, Safari and FF, but fails in IE8:

var styleElement = document.createElement("style");

styleElement.type = "text/css";

styleElement.innerHTML = "body{background:red}";

document.head.appendChild(styleElement);

In IE8, the code fails when it comes to the innerHTML part. I've tried doing:

var inner = document.createTextNode("body{background:red}");

styleElement.appendChild(inner);

But this also fails with "Unexpected call to method or property access." I'm looking for a workaround or fix.


回答1:


Use .styleSheet.cssText

NOTE: this seems to be REALLY slow in IE8 compared to modifying individual elements style.

Is there a faster way to modify style sheets dynamically in IE?

This is slow in IE8:

styleElement.styleSheet.cssText = "body{background:red}";

This is also slow in IE8 (assumes the style object to be modified is the 1st style element in the head):

document.styleSheets[0].cssText = "body{background:red}";

This is fast in IE8:

document.body.style.background = "red";



回答2:


Try to use styleElement.innerText



来源:https://stackoverflow.com/questions/6631871/modifying-the-innerhtml-of-a-style-element-in-ie8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!