日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

JavaScript window.getComputedStyle()

發(fā)布時(shí)間:2025/3/15 52 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JavaScript window.getComputedStyle() 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

?

一、window.getComputedStyle()

?

getComputedStyle?是一個(gè)可以獲取當(dāng)前元素所有最終使用的 CSS 屬性值。返回的是一個(gè) CSS 樣式聲明對(duì)象 ([object CSSStyleDeclaration]),只讀。

?

?

二、getComputedStyle 與 style 的區(qū)別

?

1. 只讀與可寫(xiě)

正如上面提到的?getComputedStyle?方法是只讀的,只能獲取樣式,不能設(shè)置;而?element.style?能讀能寫(xiě),能屈能伸。

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è)元素的高度,可以這樣寫(xiě):

element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)).height

?

?

五、getPropertyValue 方法與 getAttribute 方法

?

getPropertyValue方法可以獲取 CSS 樣式申明對(duì)象上的屬性值(直接屬性名稱(chēng)):

window.getComputedStyle(element, null).getPropertyValue("float");

如果我們不使用?getPropertyValue?方法,直接使用鍵值訪(fǎng)問(wèn),也是可以的。但是,比如這里的的float,如果使用鍵值訪(fǎng)問(wèn),就要寫(xiě)成?cssFloat?與?styleFloat,自然需要瀏覽器判斷了,比較麻煩!

getPropertyValue 方法同樣不支持 IE6 ~ IE8,所以西需要使用?getAttribute 兼容 IE 瀏覽器(需要駝峰寫(xiě)法)。

?

?

六、總結(jié)

?

最終,想要使用 getComputedStyle 方法獲取元素的屬性的兼容性寫(xiě)法:

?

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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。