CSS 控制頁面有四種方式:行內樣式(內聯)、內嵌樣式、鏈接式與導入式。
行內樣式寫在標籤的 style 屬性裡,例如 <div style="width:100px;height:100px;"></div>;內嵌樣式寫在 style 標籤中,例如 <style type="text/css">div{width:100px; height:100px}</style>;鏈接式用 link 引入外部檔,例如 <link href="test.css" type="text/css" rel="stylesheet" />;導入式則用 @import url("test.css")。
想用 JavaScript 讀取元素樣式,第一直覺通常是 element.style。但這個屬性只反映行內樣式。若元素的樣式一部分寫在行內、一部分寫在外部 CSS 檔中,透過 style 是拿不到完整資訊的。此時需要的是計算樣式(computed style)。
window.getComputedStyle 接受兩個參數:第一個是要查詢的元素,第二個可以是 null、空字串或偽類(如 :before、:after),兩者皆為必要參數。
<style type="text/css">
#testDiv {
border: 1px solid red;
width: 100px;
height: 100px;
color: red;
}
</style>
<div id="testDiv"></div>
<script>
var testDiv = document.getElementById("testDiv");
var computedStyle = window.getComputedStyle(testDiv, "");
var width = computedStyle.width; // 100px
var height = computedStyle.height; // 100px
var color = computedStyle.color; // rgb(255, 0, 0)
</script>
注意:取到的顏色一律以 rgb(#,#,#) 格式回傳。此時若改用 testDiv.style.width,結果必定是空字串。
getComputedStyle 在 IE8 及更早版本中並未實作,但 IE 的每個元素都有自己的 currentStyle 屬性。因此實務上會這樣寫:
var testDiv = document.getElementById("testDiv");
var styleInfo = window.getComputedStyle
? window.getComputedStyle(testDiv, "")
: testDiv.currentStyle;
var width = styleInfo.width; // 100px
var height = styleInfo.height; // 100px
var color = styleInfo.color; // rgb(255, 0, 0)
最後別忘了:計算樣式是唯讀的。想修改元素樣式,还是得回到 element.style——這才是 style 屬性真正的用途所在。