如何获取元素样式

元素的style属性时常被用于获取元素样式,但很多时候它是不奏效的。看下面的代码:

<html>
<body>
    <style>
        #ex2 {height:100px;width:100px;background:blue;}
    </style>
    <div style="height:100px;width:100px;background:green;" id='ex1'></div>
    <div id='ex2'></div>
    <script>
        var elem1 = document.getElementById('ex1');
        alert(elem1.style.width);
        var elem2 = document.getElementById('ex2');
        alert(elem2.style.width);
    </script>
</body>
</html>
我们发现,elem1 的值是可以取到的( 100px ),但 elem2 则是空。这是因为, style 属性只能获取内联样式。那么对于非内联样式我们应该如何取得其值呢?微软和 W3C 都提供了解决方案。

微软方案
使用currentStyle属性,它的工作方式很像style属性,但你不能通过它设置样式。
例如:

var x = document.getElementById(‘test’);
alert(x.currentStyle.color);
W3C方案
使用window.getComputedStyle() 方法,这个方法的使用略复杂。
例如:
var x = document.getElementById(‘test’);
alert(window.getComputedStyle(x, null).color);
整合两种解决方案,我们给出函数
function getRealStyle(elem, styleName){
    var realStyle = null;
    //微软
    if (elem.currentStyle){
        realStyle = elem.currentStyle[styleName];
    }
    //W3C
    else if (window.getComputedStyle){
        realStyle = window.getComputedStyle(elem, null)[styleName];
    }
    return realStyle;
}
使用这个函数,我们可以得到 elem2 的正确值 100px

代码如下:

var elem2 = document.getElementById('ex2');
alert(getRealStyle(elem2, 'width'));

注:
getComputedStyle()总是返回一个像素值(**px),即使我们在css中定义是样式是11%或是50em

参考:ppkjavascript9章 CSS修改 A style属性



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值