javascript
JavaScript window.getComputedStyle()
?
一、window.getComputedStyle()
?
getComputedStyle?是一個(gè)可以獲取當(dāng)前元素所有最終使用的 CSS 屬性值。返回的是一個(gè) CSS 樣式聲明對(duì)象 ([object CSSStyleDeclaration]),只讀。
?
?
二、getComputedStyle 與 style 的區(qū)別
?
1. 只讀與可寫
正如上面提到的?getComputedStyle?方法是只讀的,只能獲取樣式,不能設(shè)置;而?element.style?能讀能寫,能屈能伸。
2.?獲取的對(duì)象范圍
getComputedStyle?方法獲取的是最終應(yīng)用在元素上的所有 CSS 屬性對(duì)象(即使沒(méi)有 CSS 代碼);而?element.style?只能獲取元素?style?屬性中的 CSS 樣式。因此對(duì)于一個(gè)光禿禿的元素<p>,getComputedStyle?方法返回對(duì)象中?length?屬性值(如果有)就是190+(據(jù)我測(cè)試 FF:192, IE9:195, Chrome:253, 不同環(huán)境結(jié)果可能有差異), 而?element.style?就是0。
?
?
三、window.getComputedStyle 與 document.defaultView.getComputedStyle
?
jQuery 源代碼,其?css()?方法實(shí)現(xiàn)不是使用的?window.getComputedStyle?而是?document.defaultView.getComputedStyle,其實(shí)是等價(jià)的,但是有一點(diǎn),在 FireFox3.6 上只能使用?defaultView?方法搞定框架(frame)樣式。
?
?
四、getComputedStyle 與 currentStyle
?
getComputedStyle 并不支持 IE6 ~ IE8,所以需要使用?currentStyle 兼容?IE 瀏覽器。所以想獲取一個(gè)元素的高度,可以這樣寫:
element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)).height?
?
五、getPropertyValue 方法與 getAttribute 方法
?
getPropertyValue方法可以獲取 CSS 樣式申明對(duì)象上的屬性值(直接屬性名稱):
window.getComputedStyle(element, null).getPropertyValue("float");如果我們不使用?getPropertyValue?方法,直接使用鍵值訪問(wèn),也是可以的。但是,比如這里的的float,如果使用鍵值訪問(wèn),就要寫成?cssFloat?與?styleFloat,自然需要瀏覽器判斷了,比較麻煩!
getPropertyValue 方法同樣不支持 IE6 ~ IE8,所以西需要使用?getAttribute 兼容 IE 瀏覽器(需要駝峰寫法)。
?
?
六、總結(jié)
?
最終,想要使用 getComputedStyle 方法獲取元素的屬性的兼容性寫法:
?
var oStyle = this.currentStyle? this.currentStyle : window.getComputedStyle(this, null); if (oStyle.getPropertyValue) { alert("getPropertyValue下背景色:" + oStyle.getPropertyValue("background-color")); } else { alert("getAttribute下背景色:" + oStyle.getAttribute("backgroundColor")); }?
?
參考:http://www.zhangxinxu.com/wordpress/?p=2378
?
轉(zhuǎn)載于:https://www.cnblogs.com/xiaochechang/p/5932319.html
總結(jié)
以上是生活随笔為你收集整理的JavaScript window.getComputedStyle()的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 6-1:STL简介
- 下一篇: C++设计模式-Builder建造者模式