要想获取HTML元素的计算样式一直都存在很多的兼容问题,各浏览器都会存在一些差异,Firefox、webkit(Chrome,Safari)支持W3C标准的方法:getComputedStyle(),而IE6/7/8不支持标准的方法但是有私有的属性来实现:currentStyle,IE9和Opera两个都支持。有了这2个方法和属性基本上可以满足大多数要求了。
[url=http://wirelesscasinogames.com] // 获取元素在IE6/7/8中的宽度和高度
if( (p === "width" || p === "height") && val === "auto" ){
var rect = elem.getBoundingClientRect();
return ( p === "width" ? rect.right - rect.left : rect.bottom - rect.top ) "px";
}
// 获取元素在IE6/7/8中的透明度
if( p === "opacity" ){
var filter = elem.currentStyle.filter;
if( /opacity/.test(filter) ){
val = filter.match( /\d / )[0] / 100;
return (val === 1 || val === 0) ? val.toFixed(0) : val.toFixed(1);
}
else if( val === undefined ){
return "1";
}
}
// 处理top、right、bottom、left为auto的情况
if( rPos.test(p) && val === "auto" ){
return "0px";
}
return val;
}();
};
下面是调用示例:
<style>
.box{
width:500px;
height:200px;
background:#000;
filter:alpha(opacity=60);
opacity:0.6;
}
</style>
<div id="box"></div>
<script>
var box = document.getElementById( "box" );
alert( getStyle(box, "width") ); // "500px"
alert( getStyle(box, "background-color") ); // "rgb(0, 0, 0)" / "#000"
alert( getStyle(box, "opacity") ); // "0.6"
alert( getStyle(box, "float") ); // "none"
</script>