1. 程式人生 > >js中style,currentStyle和getComputedStyle的區別

js中style,currentStyle和getComputedStyle的區別

偽類 pro null prop obj 解決 strong 語法 nts

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的區別