天天看點

擷取元素CSS值getComputedStyle()

一、getComputedStyle是what?

話說我最近正在看原生代碼的時候,碰到了個眼熟的(我最近眼熱,看碎都是熟的),雖說知道他的用法和功能,但是一直沒有往深處了解下,是以就到标準上看了下簡介

This method is used to get the computed style as it is defined in [CSS2]

           

getComputedStyle()是擷取目前元素所有最終使用的CSS屬性值的方法,其傳回值是一個隻可讀取的CSS樣式聲明對象(CSSStyleDeclaration)。

The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
           

其文法如下:

var style = window.getComputedStyle(element[, pseudoElt]);
           

第一個參數是必須是element對象(如果不是element節點,将會抛出錯誤),且不可省略。第二個參數雖說可以省略,但為了相容性,在不是僞類的情況下建議設定為null

getComputedStyle 傳回的對象跟 element 調用 style 屬性傳回的對象是同一種類型,都為 CSSStyleDeclaration對象。但是這兩者有着不同的用處,getComputedStyle 傳回的是隻讀對象,用于檢測元素的樣式,而style則是可讀可寫,用于設定元素上的樣式;第二個不同之處就在于getComputedStyle()會将最終應用在元素上的所有CSS屬性對象都讀取出來(無論有米有應用到該css樣式),style則隻能擷取元素style屬性中的CSS樣式。

二、浏覽器相容

擷取元素CSS值getComputedStyle()

三、getDefaultComputedStyle()方法

getDefaultComputedStyle()方法是非标準的,目前是隻有火狐浏覽器支援,不過他的功能和調用文法和getComputedStyle()方法大緻是一樣一樣的

var style = window.getDefaultComputedStyle(element[, pseudoElt]);
           

四、currentStyle

目前支援currentStyle()方法的隻有IE浏覽器(Opera浏覽器為Presto核心時支援該方法,最新版本的Opera浏覽器是WebKit核心,已經不支援該方法)傳回的是元素目前應用的最終CSS屬性值(包括外鍊CSS檔案,以及style中的屬性等)。

擷取一個元素的所有最終使用的CSS屬性值相容性方法:

五、getPropertyValue()與getAttribute()

getPropertyValue(): 擷取CSS樣式上指定的屬性值。

文法為:

window.getComputedStyle(element, null).getPropertyValue('float')
           

如果不使用該方法擷取屬性值,也可以直接鍵值通路。

but…………

有些浏覽器通路同一屬性但鍵值不同就得判斷下浏覽器,有些屬性(比如馬margin-top)需要書寫駝峰形式,直接使用getPropertyValue()則可不必這樣麻煩(我是懶人一枚……)。

浏覽器相容性:

擷取元素CSS值getComputedStyle()

getAttribute(): 與getPropertyValue()類似的功能,擷取CSS樣式對象上指定的屬性(該方法是針對ie下的)。

總結:

雖然現在的js庫很多也很優秀,在平時的工作中有這些庫就可以火力全開了,不過私下裡還是多了解熟悉下底層的js技術,畢竟自己了解的才能變成自己的知識庫,地基牢固才有立足的根本。

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle

https://developer.mozilla.org/en-US/docs/Web/API/Window/getDefaultComputedStyle

繼續閱讀