cssRules的style不仅可以读取,还可以写入属性值。
【示例】在下面示例中,样式表中包含3个样式,其中蓝色样式类(.blue)定义字体显示为蓝色。然后用脚本修改该样式类(.blue规则)字体颜色为浅灰色(#999)。
<style type="text/css">
#box { color:green; }
.red { color:red; }
.blue { color:blue; }
</style>
<script>
window.onload = function(){
var cssRules = document.styleSheets[0].cssRules || document.styleSheets[0].rules;
cssRules[2].style.color="#999"; //修改样式表中指定属性的值
}
</script>
<p class="blue">原为蓝色字体,现在显示为浅灰色。</p>
【提示】
上述方法修改样式表中的类样式,会影响其他对象或其他文档对当前样式表的引用,因此在使用时请务必谨慎。