用 JS 讀寫樣式時,能不能拿到值往往取決於樣式寫在哪裡。以下分三種情況說明,並給出跨瀏覽器的相容解法。
<div id ="myDiv" style="width:100px;height:100px;background-color:red; border:1px solid black;"></div>
<script>
var myDiv = document.getElementById("myDiv");
alert(myDiv.style.width);//100px
alert(myDiv.style['height']);//100px
var style=myDiv.style;
alert(style.backgroundColor);//red
myDiv.style.backgroundColor='green';//myDiv背景色變為綠色
</script>
這種情況下只靠 style 屬性就足夠,因為 element.style 回傳的是一組類似陣列的樣式屬性與對應值,因此存取時有兩種寫法:ele.style.屬性名稱 與 ele.style['屬性名稱']。
要注意的是,CSS 中 background-color、margin-left 這類以短槓連接的名稱,透過 style 存取時必須改成駝峰式,例如 ele.style.backgroundColor。
style 屬性只能讀到行內樣式,但現代網頁普遍遵循樣式與結構分離,樣式多半寫在外部或內部樣式表中,因此必須換方法,而這裡就出現了瀏覽器差異:
(2.1)非 IE 瀏覽器:使用 document.defaultView 物件的 getComputedStyle(ele, null) 方法。它接受兩個參數,第一個是要考察的元素;第二個在只考察元素本身時傳 null,要考察偽類時傳對應的偽類名稱。它回傳的是元素最終套用的樣式組合,同樣是類似陣列的物件。
(2.2)IE 瀏覽器:不支援 getComputedStyle(),但每個標籤元素都有一個近似 style 的 currentStyle 屬性,用法與 style 相同,只是取得的樣式範圍不同——currentStyle 取得的結果與 getComputedStyle() 相當接近。
依據上述差異做特性檢測,就能寫出一個兩邊都能用的取值函式:
<style type="text/css">
#myDiv {
background-color:blue;
width:100px;
height:200px;
}
</style>
<div id ="myDiv" style="background-color:red; border:1px solid black;"></div>
<script>
var myDiv = document.getElementById("myDiv");
var finalStyle = myDiv.currentStyle ? myDiv.currentStyle : document.defaultView.getComputedStyle(myDiv, null);
/*利用判斷是否支持currentStyle(是否為ie) 來通過不同方法獲取style*/
alert(finalStyle.backgroundColor); //"red"
alert(finalStyle.width); //"100px"
alert(finalStyle.height); //"200px"
</script>
這個範例刻意讓行內樣式寫 red、樣式表寫 blue,結果讀出來是 red,正好驗證了「最終套用的樣式」這個概念——行內樣式的優先級高於樣式表。而 height 只存在樣式表中,也照樣能讀到 200px。
實務上把這段邏輯抽成 getStyle(obj, attr) 之類的工具函式,後續做動畫或尺寸計算時就能反覆使用,不必每次重新判斷瀏覽器。