一、getComputedStyle()
方法
一、getComputedStyle()
該
window.getComputedStyle()
方法傳回一個對象,該對象在應用活動樣式表并解析這些值可能包含的任何基本計算後,報告元素的所有
CSS
屬性的值。
單個
CSS
屬性值通過對象提供的
API
或通過使用
CSS
屬性名稱進行索引來通路。
getComputedStyle()
方法文法
getComputedStyle()
// 傳回元素的所有CSS屬性的計算值
var style = window.getComputedStyle(element [,pseudoElt ]);
-
要擷取其計算風格的element
。Element
-
(可選的)指定要比對的僞元素的字元串。必須省略(或pseudoElt
)正常元素。null
注:在
Gecko 2.0(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)
之前,需要參數
pseudoElt
。如果為
null
,則不需要指定此參數的其他主要浏覽器。
Gecko
已被更改為與其他浏覽器的行為相比對。傳回的style是一個活動
CSS StyleDeclaration
對象,它在元素的樣式更改時自動更新
getComputedStyle()
方法示例
getComputedStyle()
// 示例1
var my_div = document.getElementById("myID");
var style = window.getComputedStyle(my_div, null);
// 相當于
var style = document.defaultView.getComputedStyle(my_div, null);
// 示例2
var test = window.getComputedStyle(document.body,null);
var width = test['width'];
var height = document.documentElement.clientHeight; // 螢幕的目前寬度
$('.walletModule').css({'width': width, 'height': height});
二、 getComputedStyle
和 element.style
的差別
getComputedStyle
element.style
相同點:
二者傳回的都是
CSS StyleDeclaration
對象,取相應屬性值得時候都是采用的
CSS
駝峰式寫法,均需要注意
float
屬性
不同點:
element.style
讀取的隻是元素的内聯樣式,即寫在元素的 style 屬性上的樣式;而
getComputedStyle
讀取的樣式是最終樣式,包括了内聯樣式、嵌入樣式和外部樣式。
element.style
既支援讀也支援寫,通過
element.style
即可改寫元素的樣式;而
getComputedStyle
僅支援讀并不支援寫入
通過使用
getComputedStyle
讀取樣式,通過
element.style
修改樣式
三、相容性
-
在getComputedStyle
和Chrome
是支援該屬性的,同時Firefox
也是支援相同的特性的,IE 9 10 11
不支援。IE 8
-
屬性element.style
支援,隻是在IE 8
的支援上,float
支援的是IE 8
styleFloat