DIV CSS 佈局教程網

原生 JavaScript 取得元素樣式:五種寫法與跨瀏覽器封裝
編輯:關於JavaScript     

開發時經常需要讀取或修改 DOM 元素的樣式。修改的方式很多,改 class 是最常見的一種;而「讀取」這件事看似理所當然,實際上卻藏著幾個完全不同的 API,行為也不一致。這裡要討論的是純原生取得樣式的方法——注意,是取得,不是設定。

先定義一下目標:我們想要的是「最終套用在元素上的所有 CSS 屬性」。也就是說,即使開發者沒有為元素寫任何樣式,也應該能拿到瀏覽器的預設值。

1. ele.style:只能讀到行內樣式

學 DOM 時最早接觸到的就是 ele.style,但有時候它會回傳空字串。原因是 ele.style 只讀得到寫在該元素標籤 style 屬性裡的樣式,對於放在 <style></style> 或透過外部 CSS 檔載入的規則,它一概看不到。

var test = document.getElementById("test");
test.style.color;   // 只有行內寫了 style="color:..." 才有值

2. getComputedStyle():拿到最終計算值

這個方法會回傳元素所有「最終採用」的 CSS 屬性值,也就是瀏覽器實際用來繪製的結果。

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

它接受兩個參數:要查詢的元素,以及一個偽元素字串(例如 ":before")。不需要偽元素資訊時,第二個參數傳 null 即可。也可以寫成 document.defaultView.getComputedStyle(...)。

var test = document.getElementById("test"),
    demo = window.getComputedStyle(test, null);
demo.color;

注意兩點:Firefox 與 Safari 會把顏色轉成 rgb 格式;可以用 style.length 查看這個元素到底有多少個計算樣式(即使什麼都沒設也會有預設值)。IE6–8 不支援此方法。

3. ele.currentStyle:IE 的對應方案

currentStyle 是 IE 自己加的屬性,用法和 ele.style 類似,差別在於它回傳的是元素目前最終套用的 CSS 屬性值,包含外部樣式表與頁面內嵌的 style 屬性。

var style = dom.currentStyle;
var test = document.getElementById("test"),
    demo = test.currentStyle;
demo.color;

注意:對於 border 這類複合屬性,IE 會回傳 undefined,其他瀏覽器則有的回、有的不回;但 borderLeftWidth 這種單一屬性是有值的。

4. getPropertyValue():用原始 CSS 屬性名取值

window.getComputedStyle(element, null).getPropertyValue(屬性)
var test = document.getElementById('test');
window.getComputedStyle(test, null).getPropertyValue("background-color");

注意:屬性名必須是 CSS 原始寫法,不支援駝峰式;IE6–8 不支援。

5. getAttribute:駝峰式的替代寫法

與 getPropertyValue 類似,差別在於屬性名可以用駝峰格式。這個寫法主要作為 IE6–8 的替代。

var test = document.getElementById('test');
window.getComputedStyle(test, null).getPropertyValue("backgroundColor");

小結與跨瀏覽器封裝

jQuery 的 CSS() 方法,底層正是靠 getComputedStyle 與 getPropertyValue 這兩個 API 運作。自己寫原生程式時,只要照同樣的思路做能力偵測即可:

function getStyle(ele) {
  var style = null;

  if (window.getComputedStyle) {
    style = window.getComputedStyle(ele, null);
  } else {
    style = ele.currentStyle;   // 舊版 IE
  }

  return style;
}

取得之後,用 getStyle(el).color 或 getStyle(el).getPropertyValue("background-color") 取值,就能在主流瀏覽器與舊版 IE 上得到一致的行為。若專案已不支援 IE,直接用 getComputedStyle 就是最乾淨的選擇。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved