getComputedStyle方法與currentStyle屬性獲取元素樣式

1、getComputedStyle()

getComputedStyle是一個可以獲取當前元素所有最終使用的CSS屬性值(計算之後的最終結果,如2em計算後的結果。此外,即使沒有CSS代碼,也會把默認的祖宗八代都顯示出來)。返回的是一個CSS樣式聲明對象([object CSSStyleDeclaration]),只讀

/* 語法 */
var style = window.getComputedStyle("元素", "僞類");

/* 使用 */
var dom = document.getElementById("test"),
    style = window.getComputedStyle(dom , ":after");

額外提示下:Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) 之前,第二個參數“僞類”是必需的(如果不是僞類,設置爲null),不過現在嘛,不是必需參數了。

2、getComputedStyle()與style的區別

我們使用element.style也可以獲取元素的CSS樣式聲明對象,但是其與getComputedStyle方法還有有一些差異的。

1、 只讀與可寫
getComputedStyle方法只讀,只能獲取樣式,不能設置;
而element.style能讀能寫,能屈能伸。

2、獲取的對象範圍
getComputedStyle方法獲取的是最終應用在元素上的所有CSS屬性對象(即使沒有CSS代碼,也會把默認的祖宗八代都顯示出來);
而element.style只能獲取元素style屬性中的CSS樣式。

因此對於一個光禿禿的元素<p>,getComputedStyle方法返回對象中length屬性值(如果有)就是190+(據我測試FF:192, IE9:195, Chrome:253, 不同環境結果可能有差異), 而element.style就是0。

3、getComputedStyle與defaultView

jQuery源代碼的css()方法實現不是使用window.getComputedStyle而是document.defaultView.getComputedStyle

實際上,使用defaultView基本上是沒有必要的,getComputedStyle本身就存在window對象之中。

4、getComputedStyle兼容性

主流瀏覽器一般都支持,IE9+支持,IE6~8是不支持的。

5、IE的currentStyle屬性

element.currentStyle,與element.style的 差別在於element.currentStyle返回的是元素當前應用的最終CSS屬性值(包括外鏈CSS文件,頁面中嵌入的<style>屬性等)。

因此,從作用上將,getComputedStyle方法與currentStyle屬性走的很近,形式上則style與currentStyle走的近。不過,currentStyle屬性貌似不支持僞類樣式獲取,這是與getComputedStyle方法的差異,也是jQuery css()方法無法體現的一點。

//兼容代碼
 var oStyle = this.currentStyle? this.currentStyle : window.getComputedStyle(this, null);
    alert(oStyle.height);

6、getPropertyValue方法與getAttribute方法

getComputedStyle方法與currentStyle屬性其他具體差異還有很多,如FireFox瀏覽器下的float屬性爲‘cssFloat’,IE下爲‘styleFloat’。

使用getPropertyValue或getAttribute方法就不需要對cssFloat與styleFloat的怪異寫法與兼容性處理。

window.getComputedStyle(element, null).getPropertyValue("float");
style.getPropertyValue("border-top-left-radius");
//getPropertyValue不支持駝峯寫法
style.getAttribute("float");
style.getAttribute("backgroundColor");
/ /getAttribute只支持駝峯寫法

// 如果不考慮IE6瀏覽器,貌似也是可以這麼寫:
style.getAttribute("background-color");

7、寫在最後

有了jQuery等優秀庫,我們有熟悉底層的getComputedStyle方法的必要嗎?
類似css()方法沒有的功能——獲取僞類元素樣式。但從這一點上將,熟悉getComputedStyle方法有必要。

參考:張鑫旭http://www.zhangxinxu.com/wordpress/2012/05/getcomputedstyle-js-getpropertyvalue-currentstyle/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章