添加样式

课后整理 2020-12-20

使用addRule()方法可以为样式表增加一个样式。具体用法如下:

styleSheet.addRule(selector,style ,[index])

styleSheet表示样式表引用,参数说明如下:

Firefox支持使用insertRule()方法添加样式。用法如下:

styleSheet.insertRule(rule  ,[index])

参数说明如下:

【示例】在下面示例中,先在文档中定义一个内部样式表,然后使用styleSheets集合获取当前样式表,利用数组默认属性length获取样式表中包含的样式个数。最后在脚本中使用addRule()(或insertRule())方法增加一个新样式,样式选择符为p,样式声明为背景色为红色,字体颜色为白色,段落内部补白为1个字体大小。

<style  type="text/css">
#box  { color:green; }
.red  { color:red; }
.blue  { color:blue; }
</style>
<script>
window.onload  = function(){
       var styleSheets =  document.styleSheets[0];   //获取样式表引用
       var index = styleSheets.length;                   //获取样式表中包含样式的个数
       if(styleSheets.insertRule){                          //判断浏览器是否支持insertRule()方法
              //在内部样式表中增加p标签选择符的样式,插入样式表的末尾,
              styleSheets.insertRule("p{background-color:red;color:#fff;padding:1em;}",  index);
       }else{                                                      //如果浏览器不支持insertRule()方法
              styleSheets.addRule("P",  "background-color:red;color:#fff;padding:1em;", index);
       }
}
</script>
<p>在样式表中增加样式操作</p>