document.body.style.color = "white"
例如,要为主体设置样式,可以简单地执行,但是如果我想对pre
-tag做同样的事情,该怎么做?
最好的解决方案是使用类来更改样式。这通常是主题的工作方式。您可以在主体上设置一个类,以更改要更改的事物。
window.setTimeout( function () {
document.body.classList.add("luckyGreen")
}, 4000)
window.setTimeout( function () {
document.body.classList.remove("luckyGreen")
}, 8000)
pre {
background-color: #CCC;
}
body.luckyGreen {
color:green;
}
body.luckyGreen pre {
background-color: #CFC;
}
<pre>
Hello there
</pre>
X
<pre>
Hello there
</pre>
Y
<pre>
Hello there
</pre>
但是出于某种原因,您想更改类,可以编写新的CSS规则。
function addRule() {
var styleEl = document.createElement('style');
document.head.appendChild(styleEl);
var styleSheet = styleEl.sheet;
var ruleStr = "pre { background-color: red; }"
styleSheet.insertRule(ruleStr, styleSheet.cssRules.length);
}
window.setTimeout(addRule, 4000)
<pre>
Hello there
</pre>
X
<pre>
Hello there
</pre>
Y
<pre>
Hello there
</pre>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句