javascript
JavaScript window.getComputedStyle()
?
一、window.getComputedStyle()
?
getComputedStyle?是一個可以獲取當前元素所有最終使用的 CSS 屬性值。返回的是一個 CSS 樣式聲明對象 ([object CSSStyleDeclaration]),只讀。
?
?
二、getComputedStyle 與 style 的區別
?
1. 只讀與可寫
正如上面提到的?getComputedStyle?方法是只讀的,只能獲取樣式,不能設置;而?element.style?能讀能寫,能屈能伸。
2.?獲取的對象范圍
getComputedStyle?方法獲取的是最終應用在元素上的所有 CSS 屬性對象(即使沒有 CSS 代碼);而?element.style?只能獲取元素?style?屬性中的 CSS 樣式。因此對于一個光禿禿的元素<p>,getComputedStyle?方法返回對象中?length?屬性值(如果有)就是190+(據我測試 FF:192, IE9:195, Chrome:253, 不同環境結果可能有差異), 而?element.style?就是0。
?
?
三、window.getComputedStyle 與 document.defaultView.getComputedStyle
?
jQuery 源代碼,其?css()?方法實現不是使用的?window.getComputedStyle?而是?document.defaultView.getComputedStyle,其實是等價的,但是有一點,在 FireFox3.6 上只能使用?defaultView?方法搞定框架(frame)樣式。
?
?
四、getComputedStyle 與 currentStyle
?
getComputedStyle 并不支持 IE6 ~ IE8,所以需要使用?currentStyle 兼容?IE 瀏覽器。所以想獲取一個元素的高度,可以這樣寫:
element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)).height?
?
五、getPropertyValue 方法與 getAttribute 方法
?
getPropertyValue方法可以獲取 CSS 樣式申明對象上的屬性值(直接屬性名稱):
window.getComputedStyle(element, null).getPropertyValue("float");如果我們不使用?getPropertyValue?方法,直接使用鍵值訪問,也是可以的。但是,比如這里的的float,如果使用鍵值訪問,就要寫成?cssFloat?與?styleFloat,自然需要瀏覽器判斷了,比較麻煩!
getPropertyValue 方法同樣不支持 IE6 ~ IE8,所以西需要使用?getAttribute 兼容 IE 瀏覽器(需要駝峰寫法)。
?
?
六、總結
?
最終,想要使用 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
?
轉載于:https://www.cnblogs.com/xiaochechang/p/5932319.html
總結
以上是生活随笔為你收集整理的JavaScript window.getComputedStyle()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 6-1:STL简介
- 下一篇: MVC中Spring.net 对基类控制