Js获取元素样式值(getComputedStyle&currentStyle)兼容性解决方案

因为:style(document.getElementById(id).style.XXX)只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的。

 

一般js获取内部样式和外部样式使用getComputedStyle,以及currentStyle。

 

IE下获取元素的实际属性值使用currentStyle属性,getComputedStyle同currentStyle作用相同,但是适用于FF、opera、safari、chrome。但用这种方法在IE7,IE8,IE9获取元素属性值都会报错。

 

出于对兼容性的考虑,故将两种获取的方法封装在同一个函数中,使其见招拆招,遇到不同的浏览器,自动采取相适应的方法:

 

<script type="text/javascript">

function getStyle (obj,attr) {

return obj.currentStyle ? obj.currentStyle[attr]:getComputedStyle(obj)[attr];

}

</script>

  

 



 

注意在IE下,如果没有显示的设置元素的值,那么使用该方法获取的值为auto。

 

<body></body>

<script>

getStyle(document.body,'height');

</script>

  

 

 

 

  

IE6/7/8/9中输出的都是auto。如果显示的设置了宽高,那么输出的就是实际宽高。

 

 

css:

body{height:120px;}

<body></body>

<script>

getStyle(document.body,'height');

</script>

  

 

 



posted @ 2015-06-01 11:47  Me-Kevin  阅读(2013)  评论(0编辑  收藏  举报