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

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

1var 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就是高度。我对他的代码做了一些小小的修改,最终代码如下:

01var 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// 调用该方法
24var 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/archive/2013/03/11/2954138.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值