CSSOM之getComputedStyle,currentStyle,getPropertyValue,getAttribute
js關于CSSOM編程的樣式相關幾個常用的方法
webkit:getComputedStyle,getPropertyValue
IE:currentStyle,getAttribute
前言
jquery 中的 css() 方法,其底層運用的就是?getComputedStyle,getPropertyValue 方法。
getComputedStyle
getComputedStyle 是一個可以獲取當前元素所有最終使用的css屬性值的方法。返回一個CSSStyleDeclaretion 實例的對象。只讀
語法如下:
var style = window.getComputedStyle("元素", "偽類");例如:
var dom = document.getElementById("test"),style = window.getComputedStyle(dom , ":after");getComputedStyle與style的區別
我們使用element.style也可以獲取元素的CSS樣式聲明對象,但是其與getComputedStyle方法還有有一些差異的。
1.element.style 屬性可讀可寫
2.getComputedStyle 返回的是元素最終的樣式,而element.style 只是style屬性的值
注意:getComputedStyle 方法在 window ,和document.defaultView 上
window.getComputedStyle===document.defaultView.getComputedStyle 返回True.getComputedStyle與currentStyle
currentStyle是IE瀏覽器自娛自樂的一個屬性,其與element.style可以說是近親,至少在使用形式上類似,element.currentStyle,差別在于element.currentStyle返回的是元素當前應用的最終CSS屬性值(包括外鏈CSS文件,頁面中嵌入的<style>屬性等)。
因此,從作用上將,getComputedStyle方法與currentStyle屬性走的很近,形式上則style與currentStyle走的近。不過,currentStyle屬性貌似不支持偽類樣式獲取,這是與getComputedStyle方法的差異,也是jQuery?css()方法無法體現的一點。
getPropertyValue
getPropertyValue方法可以獲取CSS樣式申明對象上的屬性值(直接屬性名稱),例如:
window.getComputedStyle(element, null).getPropertyValue("float");
如果我們不使用getPropertyValue方法,直接使用鍵值訪問,其實也是可以的。但是,比如這里的的float,如果使用鍵值訪問,則不能直接使用getComputedStyle(element, null).float,而應該是cssFloat與styleFloat,自然需要瀏覽器判斷了,比較折騰!
使用getPropertyValue方法不必可以駝峰書寫形式(不支持駝峰寫法),例如:style.getPropertyValue("border-top-left-radius");
兼容性
getPropertyValue方法IE9+以及其他現代瀏覽器都支持,
OK,一涉及到兼容性問題(IE6-8腫么辦),感覺頭開始微微作痛了~~,不急,IE自由一套自己的套路,就是getAttribute方法
getPropertyValue和getAttribute
在老的IE瀏覽器(包括最新的),getAttribute方法提供了與getPropertyValue方法類似的功能,可以訪問CSS樣式對象的屬性。用法與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"));}}; }?
轉載于:https://www.cnblogs.com/btgyoyo/p/6159697.html
總結
以上是生活随笔為你收集整理的CSSOM之getComputedStyle,currentStyle,getPropertyValue,getAttribute的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IDEA启动自动进入最后一个项目
- 下一篇: Android简易实战教程--第四十七话