CSS样式具有重叠特性,因此定义的样式与最终显示的样式并非完全相同。DOM定义了一个方法帮助用户快速检测当前对象的显示样式,不过IE和标准DOM之间实现的方法不同。
- IE浏览器
IE使用currentStyle对象读取元素的最终显示样式,为一个只读对象。currentStyle对象包含元素的style属性,以及浏览器预定义的默认style属性。
【示例1】针对上节示例,把类样式blue增加了一个背景色为白色的声明,然后把该类样式应用到段落文本中。
<style type="text/css">
#box { color:green; }
.red { color:red; }
.blue {
color:blue;
background-color:#FFFFFF;
}
</style>
<script>
window.onload = function(){
var styleSheets = document.styleSheets[0]; //获取样式表引用
var index = styleSheets.length; //获取样式表中包含样式的个数
if(styleSheets.insertRule){ //判断是否支持insertRule()方法
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 class="blue">在样式表中增加样式操作</p>
在浏览器中预览,会发现脚本中使用insertRule()(或addRule())方法添加的样式无效。
这时可以使用currentStyle对象获取当前p元素最终显示样式。
【示例2】把上面示例另存为test1.html,然后在脚本中添加代码,使用currentStyle获取当前段落标签<p>的最终显示样式。
<script>
window.onload = function(){
var styleSheets = document.styleSheets[0]; //获取样式表引用
var index = styleSheets.length; //获取样式表中包含样式的个数
if(styleSheets.insertRule){ //判断是否支持insertRule()方法,否则调用addRule
styleSheets.insertRule("p{background-color:red;color:#fff;padding:1em;}", index);
}else{
styleSheets.addRule("P", "background-color:red;color:#fff;padding:1em;", index);
}
var p = document.getElementsByTagName("p")[0];
p.innerHTML = "背 景 色:"+p.currentStyle.backgroundColor+"<br>字体颜色:"+p.currentStyle.color;
}
</script>
在上面代码中,首先使用getElementsByTagName()方法获取段落文本的引用。然后调用该对象的currentStyle子对象,并获取指定属性的对应值。通过这种方式,会发现insertRule()(或addRule())方法添加的样式被blue类样式覆盖,这是因为类选择符的优先级大于标签选择符的样式。
- 非IE浏览器
DOM使用getComputedStyle()方法获取目标对象的显示样式,但是它属于document.defaultView对象。getComputedStyle()方法包含了两个参数:
第一个参数表示元素,用来获取样式的对象;第二个参数表示伪类字符串,定义显示位置,一般可以省略,或者设置为null。
【示例3】针对上面示例,为了能够兼容非IE浏览器,下面对页面脚本进行修改。使用if语句判断当前浏览器是否支持document.defaultView,如果支持则进一步判断是否支持document.defaultView.getComputedStyle,如果支持则使用getComputedStyle()方法读取最终显示样式;否则,判断当前浏览器是否支持currentStyle,如果支持则使用它读取最终显示样式。
<style type="text/css">
#box { color:green; }
.red { color:red; }
.blue {color:blue; background-color:#FFFFFF;}
</style>
<script>
window.onload = function(){
var styleSheets = document.styleSheets[0]; //获取样式表引用指针
var index = styleSheets.length; //获取样式表中包含样式的个数
if(styleSheets.insertRule){ //判断浏览器是否支持
styleSheets.insertRule("p{background-color:red;color:#fff;padding:1em;}", index);
}else{
styleSheets.addRule("P", "background-color:red;color:#fff;padding:1em;", index);
}
var p = document.getElementsByTagName("p")[0];
if( document.defaultView && document.defaultView.getComputedStyle)
p.innerHTML = "背 景 色:"+document.defaultView.getComputedStyle(p,null).backgroundColor+"<br>字体颜色:"+document.defaultView.getComputedStyle(p,null).color;
else if( p.currentStyle)
p.innerHTML = "背 景 色:"+p.currentStyle.backgroundColor+"<br>字体颜色:"+p.currentStyle.color;
else p.innerHTML = "当前浏览器无法获取最终显示样式";
}
</script>
<p class="blue">在样式表中增加样式操作</p>