js中style,currentStyle和getComputedStyle的區別

來源:互聯網
上載者:User

標籤: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的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.