標籤: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