開發中經常需要通過 JS 獲取或改變 DOM 元素的樣式,方法有很多,比如更改元素的 class。這裡我們討論用原生 JS 獲取 DOM 元素的 CSS 樣式(注意是獲取,不是設置)。
先說明一下,「獲取最終應用在元素上的所有 CSS 屬性對象」的意思是:即使沒有給元素設置任何樣式,也會把瀏覽器默認的樣式返回回來。
1、ele.style
學習 DOM 時就看到用 ele.style 獲取元素樣式值,但有時獲取到的並非節點樣式值,而是空值。這是因為 ele.style 只能獲取寫在元素標簽 style 屬性裡的樣式,無法獲取定義在 <style></style> 或通過 <link href="css.css"> 加載進來的樣式。
例子:
var test = document.getElementById("test"); //獲取節點的color test.style.color;
2、getComputedStyle()
getComputedStyle 可以獲取當前元素所有最終使用的 CSS 屬性值。語法如下:
window.getComputedStyle("元素", "偽類");
這個方法接受兩個參數:要取得計算樣式的元素,以及一個偽元素字符串(例如 ":before");若不需要偽元素信息,第二個參數可以是 null。也可通過 document.defaultView.getComputedStyle("元素", "偽類") 來使用。
例子:
var test = document.getElementById("test"), demo = window.getComputedStyle(test, null); //獲取節點的color demo.color
注意:Firefox 和 Safari 會把顏色轉換成 rgb 格式;若 test 節點上沒有任何樣式,可用 style.length 查看瀏覽器默認樣式的個數。IE6-8 不支持該方法,需使用下面的方法。
3、ele.currentStyle
currentStyle 是 IE 瀏覽器自己的屬性,語法與 ele.style 類似,差別在於它返回的是元素當前應用的最終 CSS 屬性值(包括外鏈 CSS、頁面嵌入的 <style> 等)。
語法:
var style = dom.currentStyle;
例子:
var test = document.getElementById("test"), demo = test.currentStyle; //獲取節點的color demo.color;
注意:對於 border 等綜合屬性,IE 返回 undefined,其他瀏覽器有的返回值有的不返回,但 borderLeftWidth 這樣的屬性是有返回值的。
4、getPropertyValue()
getPropertyValue 獲取 CSS 樣式的直接屬性名稱,語法如下:
window.getComputedStyle(element, null).getPropertyValue(屬性)
例子:
var test = document.getElementById('test'); window.getComputedStyle(test, null).getPropertyValue("background-color");
注意:屬性名不支持駝峰格式;IE6-8 不支持該方法,需使用下面的方法。
5、getAttribute
getAttribute 與 getPropertyValue 類似,差別是屬性名用駝峰格式。
例子:
var test = document.getElementById('test'); window.getComputedStyle(test, null).getAttribute("backgroundColor");
注意:該方法只支持 IE6-8。
小結:
jQuery 的 CSS() 方法,其底層運作就應用了 getComputedStyle 與 getPropertyValue。使用原生 JS 開發時,就可以通過以上方法獲取元素樣式值。
下面是一個兼容 IE、Firefox、Chrome 等瀏覽器的獲取元素樣式的方法,可直接應用到項目中:
function getStyle(ele) { var style = null; if(window.getComputedStyle) { style = window.getComputedStyle(ele, null); }else{ style = ele.currentStyle; } return style; }
以上就是原生 JS 獲取元素樣式的簡單方法,希望能給大家提供參考。