擷取元素的css屬性之getComputedStyle

來源:互聯網
上載者:User

標籤:asc   blog   屬性   current   讀取   support   null   pop   包括   

  習慣了用jQuery的css()的方法擷取元素的css屬性,突然不用jQquery了,當要獲得元素的css時候,我瞬間停頓了一下,咦?咋擷取元素的css值?比如擷取元素的width。是這樣嗎?document.getElementById("id").style.width?

一、getComputedStyle
  getComputedStyle,見名之意,就是擷取元素計算之後的樣式屬性值,也就是擷取當前元素所有最終使用的CSS屬性值。返回的是一個CSS樣式聲明對象([object CSSStyleDeclaration]),注意是唯讀。
文法:var style = window.getComputedStyle("元素", "偽類");
說明:第二個參數可以省略

如獲得元素的width:
  var ele = document.getElementById("XXX");
  var _width = window.getComputedStyle(ele).width;


二、getComputedStyle與style的區別
  1、getComputedStyle方法是唯讀,只能擷取樣式,不能設定;
  2、element.style能讀取,能設定,但是注意,只能讀取元素中style屬性中的樣式。
  3、getComputedStylen能擷取所有的css屬性,包括預設的。


三、getComputedStyle與defaultView
  defaultView又是什麼東東?jQuery擷取樣式方式就是如下:

var getStyles = function( elem ) {// Support: IE <=11 only, Firefox <=30 (#15098, #14150)// IE throws on elements created in popups// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"var view = elem.ownerDocument.defaultView;if ( !view || !view.opener ) {view = window;}return view.getComputedStyle( elem );};

  

  雖然window上命名有getComputedStyle屬性了,直接但是使用window.getComputedStyle(ele)不會有啥問題,但是在Firefox就會有問題,jQuery也在備忘中寫好了。

四、getComputedStyle相容性
  別想了,此處IE不整點名堂怎麼證明當初它式瀏覽器中的一霸主呢?
IE給自己提供了一套方法。IE中使用currentStyle代替getComputedStyle
  如獲得元素width:
  element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)).width;

擷取元素的css屬性之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.