1. 程式人生 > 實用技巧 >js_getComputed方法和style屬性關於讀取樣式的區別

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支援