获取元素的计算的样式(返回auto值getBoundingClientRect)

要想获取HTML元素的计算样式一直都存在很多的兼容问题,各浏览器都会存在一些差异,Firefox、webkit(Chrome,Safari)支持W3C标准的方法:getComputedStyle(),而IE6/7/8不支持标准的方法但是有私有的属性来实现:currentStyle,IE9和Opera两个都支持。有了这2个方法和属性基本上可以满足大多数要求了。

1 var getStyle = function( elem, type ){
2     return 'getComputedStyle' in window ? getComputedStyle(elem, null)[type] : elem.currentStyle[type];
3 };

但是对于自适应的宽度和高度使用currentStyle就没法获取到计算的值,只能返回auto,而getComputedStyle()就可以返回计算的值,解决这个问题有好几种办法。我之前想到的是用clientWidth/clientHeight减去padding的值,这样就可以在不支持标准方法的浏览器中获取到计算的宽度和高度。前几天看到司徒正美采用了另一种办法,使用getBoundingClientRect()方法获取到元素在页面中的位置,然后right减去left就是宽度,bottom减去top就是高度。我对他的代码做了一些小小的修改,最终代码如下:

01 var getStyle = function( elem, style ){
02     return 'getComputedStyle' in window ?
03     getComputedStyle( elem, null )[style] :
04     function(){
05         style = style.replace( /\-(\w)/g, function( $, $1 ){
06             return $1.toUpperCase();
07         });
08  
09         var val =  elem.currentStyle[style];
10  
11         if( val === 'auto' && (style === "width" || style === "height") ){
12             var rect =  elem.getBoundingClientRect();
13             if( style === "width" ){
14                 return rect.right - rect.left + 'px';
15             }else{
16                 return rect.bottom - rect.top + 'px';
17             }
18         }
19         return val;
20     }();
21 };
22  
23 // 调用该方法
24 var test = document.getElementById( 'test' ),
25       // 获取计算的宽度
26     tWidth = getStyle( test, 'width' );

新的问题,如果元素的宽度或高度使用了em或%的单位,getComputedStyle()返回的值就会自动将em或%换成px的单位,currentStyle就不会,而如果是font-size使用em为单位,在Opera下返回的是0em,Opera真的很恐怖!

9月24日对该getStyle进行了优化处理,详见http://stylechen.com/getstyle2.html

转:http://stylechen.com/getstyle2.html

原文地址:https://www.cnblogs.com/lyweb/p/2954138.html