原生js获取元素非行内样式属性的方法

时间:2021-10-29 22:13:43

获取当前对象的样式DOM标准中的全局方法 getComputedStyle(obj).width (获取元素的宽度),但在非标准IE浏览器(IE8)以下有兼容问题
IE8以下要这样写 obj.currentStyle.width  这样的话在IE8以下正常显示,但标准浏览器下又会报错,所以一要判断一下

//getStyle()函数,获取元素的非行内样式
//使用方法 getStyle(元素,"属性名") 如:getStyle(oBox,"background")
function getStyle(obj,attr) {
if(window.getComputedStyle){//浏览器如果支持getComputedStyle()方法
return getComputedStyle(obj)[attr];
}else{
return obj.currentStyle[attr];
}
}
obj.style.width只能获取行内元素样式
<head>
<style>
.block{
width: 100px;
height: 100px;
}
</style>
</head> <body>
  <div class="block" style="background:blueviolet;"></div>
  <script>
  var block = document.getElementsByClassName("block")[0];
 console.log(block.style.width);//什么都不输出
    console.log(block.style.background);//blueviolet
  </script>
</body>
</html>