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


获取当前对象的样式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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM