获取元素的计算的样式

3077次阅读  |  发布于5年以前

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


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

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


    var getStyle = function( elem, style ){
        return 'getComputedStyle' in window ? 
        getComputedStyle( elem, null )[style] : 
        function(){
            style = style.replace( /\-(\w)/g, function( $, $1 ){
                return $1.toUpperCase();
            });

            var val =  elem.currentStyle[style];

            if( val === 'auto' && (style === "width" || style === "height") ){
                var rect =  elem.getBoundingClientRect();
                if( style === "width" ){
                    return rect.right - rect.left + 'px';
                }else{
                    return rect.bottom - rect.top + 'px';
                }
            }
            return val;
        }();
    };

    // 调用该方法
    var test = document.getElementById( 'test' ),
          // 获取计算的宽度
        tWidth = getStyle( test, 'width' );

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

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

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8