JS获取外部样式表中的样式

               

用document.getElementById(‘element').style.xxx可以获取元素的样式信息,可是它获取的只是DOM元素style属性里的样式规则,对于通过class属性引用的外部样式表,就拿不到我们要的信息了。

兼容性处理

解决方案

处理IE,引入currentStyle,runtimeStyle,getComputedStyle style 标准的样式,可能是由style属性指定的!

通过currentStyle就可以获取到通过内联或外部引用的CSS样式的值了(仅限IE) 如:document.getElementById("test").currentStyle.top

要兼容FF,就得需要getComputedStyle 出马了!

1
2
3
4
5
<style>
#a{
      width : 300px ;
}
</style>

则:

1
2
3
4
5
6
7
8
var a = document.getElementById( 'a' );
if (typeof a.currentStyle!='undefine') {//FF
       var  width = a.currentStyle[ 'width' ];
       alert( 'ie:'  + width);
} else  if (typeof window.getComputedStyle!='undefine') {//IE
       var  width = window.getComputedStyle(a, null )[ 'width' ];
       alert( 'firefox:'  + width);
}
           

猜你喜欢

转载自blog.csdn.net/qq_44884300/article/details/89089960