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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > CSS >内容正文

CSS

CSSOM之getComputedStyle,currentStyle,getPropertyValue,getAttribute

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

js關(guān)于CSSOM編程的樣式相關(guān)幾個(gè)常用的方法

webkit:getComputedStyle,getPropertyValue

IE:currentStyle,getAttribute

前言

jquery 中的 css() 方法,其底層運(yùn)用的就是?getComputedStyle,getPropertyValue 方法。

getComputedStyle

getComputedStyle 是一個(gè)可以獲取當(dāng)前元素所有最終使用的css屬性值的方法。返回一個(gè)CSSStyleDeclaretion 實(shí)例的對(duì)象。只讀

語法如下:

var style = window.getComputedStyle("元素", "偽類");

例如:

var dom = document.getElementById("test"),style = window.getComputedStyle(dom , ":after");

getComputedStyle與style的區(qū)別

我們使用element.style也可以獲取元素的CSS樣式聲明對(duì)象,但是其與getComputedStyle方法還有有一些差異的。

1.element.style 屬性可讀可寫

2.getComputedStyle 返回的是元素最終的樣式,而element.style 只是style屬性的值

注意:getComputedStyle 方法在 window ,和document.defaultView 上

window.getComputedStyle===document.defaultView.getComputedStyle 返回True.

getComputedStyle與currentStyle

currentStyle是IE瀏覽器自娛自樂的一個(gè)屬性,其與element.style可以說是近親,至少在使用形式上類似,element.currentStyle,差別在于element.currentStyle返回的是元素當(dāng)前應(yīng)用的最終CSS屬性值(包括外鏈CSS文件,頁面中嵌入的<style>屬性等)。

因此,從作用上將,getComputedStyle方法與currentStyle屬性走的很近,形式上則style與currentStyle走的近。不過,currentStyle屬性貌似不支持偽類樣式獲取,這是與getComputedStyle方法的差異,也是jQuery?css()方法無法體現(xiàn)的一點(diǎn)。

getPropertyValue

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

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

  

如果我們不使用getPropertyValue方法,直接使用鍵值訪問,其實(shí)也是可以的。但是,比如這里的的float,如果使用鍵值訪問,則不能直接使用getComputedStyle(element, null).float,而應(yīng)該是cssFloat與styleFloat,自然需要瀏覽器判斷了,比較折騰!

使用getPropertyValue方法不必可以駝峰書寫形式(不支持駝峰寫法),例如:style.getPropertyValue("border-top-left-radius");

兼容性
getPropertyValue方法IE9+以及其他現(xiàn)代瀏覽器都支持,

OK,一涉及到兼容性問題(IE6-8腫么辦),感覺頭開始微微作痛了~~,不急,IE自由一套自己的套路,就是getAttribute方法

getPropertyValue和getAttribute

在老的IE瀏覽器(包括最新的),getAttribute方法提供了與getPropertyValue方法類似的功能,可以訪問CSS樣式對(duì)象的屬性。用法與getPropertyValue類似:

style.getAttribute("float");

?

綜上,獲取元素的兼容性樣式:

var oButton = document.getElementById("button");if (oButton) {oButton.onclick = function() {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"));}}; }

?

轉(zhuǎn)載于:https://www.cnblogs.com/btgyoyo/p/6159697.html

總結(jié)

以上是生活随笔為你收集整理的CSSOM之getComputedStyle,currentStyle,getPropertyValue,getAttribute的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

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