日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JavaScript window.getComputedStyle()

發布時間:2025/3/15 javascript 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。