js_getComputed方法和style属性关于读取样式的区别

菜鸟教程:window.getComputedStyle() 方法的使用

getComputedStyle方法的使用

  • getComputedStyle方法是window对象下的方法,它接收element的值并获取它的最终属性.
    <style>
        .div1 {
            width: 150px;
            height: 150px;
            background-color: orange;
        }
    </style>
<body>
    <div class="div1" style="background-color: rgb(150,150,150);"></div>
    <script>
        var $div1 = document.getElementsByClassName('div1')[0];
        console.log(getComputedStyle($div1).backgroundColor);//rgb(150, 150, 150)
        console.log(getComputedStyle($div1).width);//150px
        console.log(getComputedStyle($div1).src);//undefined
        console.log($div1.style.width);//undefined
        console.log($div1.style.backgroundColor);//rgb(150, 150, 150)
    </script>
</body>

如上代码所示:div1最终显示为一个长150px宽150px的灰色div盒子.

  • 通过getComputedStyle获取的背景色是灰色,style嵌入样式与style内联属性冲突时内联属性优先,getComputedStyle方法返回的是三种属性中最终显示的属性.
  • 未定义的样式属性值为undefined.
  • .style方式只能获取内联属性的值.
  • getComputedStyle方法只能读取,不能写入,.style可以读取也可以写入
  • 兼容性:chrome\firefox\IE9 10 11支持

猜你喜欢

转载自www.cnblogs.com/Syinho/p/13197401.html