getComputedStyle()屬於window對象下的一個方法,用於獲取元素的樣式屬性;該方法在MDN網站上有詳細的介紹,可點擊該鏈接https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle。
方法定義:window.getComputedStyle(元素,[偽類]),第二個參數是可選的,通常會將其設為null;
返回值為一個對象,包含該元素的所有樣式屬性;
可通過一個測試來了解getComputedStyle(),測試中通過getComputedStyle()獲取h1元素的樣式屬性,並通過控制台輸出
//css部分
#title{ width: 280px; height: 35px; color: #000; text-align: center; box-shadow: 5px 5px 5px #333; }
//html部分
<body> <h1 id="title">Hello world.</h1>
<script> var title = document.getElementById('title'), style = window.getComputedStyle(title,null); console.log(style.length);//228 for(var i in style) console.log("The property " + i + " :" + style[i]); </script>
</body>
firefox輸出頁面:
Firebug下輸出結果:
.......................
從輸出結果可知,通過getComputedStyle()方法獲取到了h1元素的228個樣式屬性,也就是說該方法並不是僅僅取得我們為元素設置的css樣式屬性,其他未設置的屬性同樣可以獲得,也即獲得最終應用在該元素上的所有樣式屬性;
當然,通常我們使用該方法是希望能知道元素上的某個樣式屬性的具體設置,那我們應該怎么做呢?其實很簡單,因為getComputedStyle()返回的是一個對象,所以我們就可以通過點引用的方式獲取相應的屬性值,如:(接着上面的測試例子)
<script>
console.log(style.width);//打印出h1的width值
</script>
輸出:
與getCOmputedStyle()方法類似還有一個IE專屬的currentStyle對象,currentStyle對象包含有獲取和設置樣式屬性值的方法,詳細介紹可看這里https://msdn.microsoft.com/en-us/library/ie/ms535231(v=vs.85).aspx
結束語:因getComputedStyle()方法是只讀的,故不能通過其去設置樣式的屬性值,設置樣式的屬性可通style對象來解決