如何通过JavaScript更改文档的样式?

Fra*_*urd 2 javascript css dom

这就像这样*{margin:0; 填充:0;} 在CSS中.

Voi*_*ter 7

要使用(第一个)样式表对象

document.styleSheets[0]
Run Code Online (Sandbox Code Playgroud)

要访问样式表中的(第一个)规则,请使用:

document.styleSheets[0].cssRules[0] // firefox
document.styleSheets[0].rules[0]    // IE
Run Code Online (Sandbox Code Playgroud)

您可以添加规则

insertRule(rule, index)                 // firefox
addRule(selector, declaration, [index]) // IE
Run Code Online (Sandbox Code Playgroud)

因此,要做你在firefox中描述的内容:

document.styleSheets[0].insertRule("*{margin:0; padding:0;}", 0) 
Run Code Online (Sandbox Code Playgroud)

并在IE中做到这一点:

document.styleSheets[0].addRule("*", "margin:0; padding:0;", 0)
Run Code Online (Sandbox Code Playgroud)

另请参见:Dom StyleSheet对象.