This question already has answers here:
How to create a <style> tag with Javascript?
                                
                                    (14个回答)
                                
                        
                                5年前关闭。
            
                    
当我创建样式元素并尝试向其附加代码时,以下代码将引发错误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; }"));


我究竟做错了什么?

最佳答案

在旧版本的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));

10-07 21:51