標籤:ati function 不能 put object c class 限制 into zha
js中style,currentStyle和getComputedStyle的區別 MarysMa 在js中用xx.style.marginTop是無法擷取寫在css或<sytle>標籤中的margin-top之類的樣式值(包括width,height等)。
這就是style屬性的限制:
style
:只能擷取元素的內聯樣式,內部樣式和外部樣式使用style是擷取不到的。(內聯樣式: body中標籤裡用style直接寫的樣式。)
currentStyle
:可以彌補style的不足,但是只適用於IE。
getComputedStyle
:同currentStyle作用相同,但是適用於FF、opera、safari、chrome。 所以相容的取值寫法:getElementStyle: function(el,attr){//擷取el當前的attr樣式,解決ie問題return el.currentStyle?el.currentStyle[attr]:getComputedStyle(el,null)[attr];}
注意:
currentStyle和getComputedStyle只能用於擷取頁面元素的樣式,不能用來設定相關值。
如果要設定相應值,應使用style。
科普:
getComputedStyle:是一個可以擷取當前元素所有最終使用的CSS屬性值。返回的是一個CSS樣式聲明對象([object CSSStyleDeclaration]),唯讀。(總而言之就是擷取一堆樣式。。。) 文法如下:var style = window.getComputedStyle("元素", "偽類"); 順帶一提jq庫的$.css()就是用getComputedStyle和getPropertyValue兩者結合。詳細可以看文章:
擷取元素CSS值之getComputedStyle方法熟悉 ? 張鑫旭
js中style,currentStyle和getComputedStyle的區別