js中怎么获取CSS属性值

obj.style:

这个方法只能获取写在style属性中的值,而无法获取定义在 <style type='text/css'>里面的属性

<style type=”text/css”> 
.ss{color:#cdcdcd;}  
</style>  
<div id=”css88″ class=”ss” style=”width:200px; height:200px; background:#333333″>JS获取CSS属性值
</div>  
<script type=”text/javascript”> 
alert(document.getElementById(“css88″).style.width);//200px 
alert(document.getElementById(“css88″).style.color);//空白 
</script> 

obj.currentStyle与getComputerStyle

obj.currentStyle只有IE支持,而getComputerStyle在FireFox中支持,这个方法接受两个参数:要取得计算样式的元素和一个伪元素字符串(例如“;after”)。如果不需要伪元素信息,第二个参数可以为null。该方法返回一个CSSStyleDeclaration对象,其中包含当前元素的所有计算的样式。

<html> 
<head> 
<title>计算元素样式</title> 
<style> 
#myDiv { 
    width:100px; 
    height:200px; 
} 
</style> 
<body> 
<div id ="myDiv" style=" border:1px solid black"></div> 
 
<script> 
var myDiv = document.getElementById("myDiv"); 
var computedStyle = document.defaultView.getComputedStyle(myDiv, null); 
 
alert(computedStyle.backgroundColor); //"red" 
alert(computedStyle.width); //"100px" 
alert(computedStyle.height); //"200px" 
alert(computedStyle.border); //在某些浏览器中是“1px solid black” 
</script> 
</body> 
</head> 
</html></span>

所以估计兼容浏览器,我们可以封装一个函数来获取一个元素的CSS属性值:

function getStyle(element, attr) {
        if(element.currentStyle) {
                return element.currentStyle[attr];
        } else {
                return getComputedStyle(element, false)[attr];
        }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值