在 JavaScript 中讀取元素的 CSS 樣式,會依樣式來源不同而採用不同方式。最簡單的是行間樣式,可直接透過 element.style 取得;若是內部樣式或外部樣式表,則通常需要 getComputedStyle 或样式表物件。
行間樣式是直接寫在 HTML 元素的 style 屬性中。這類樣式可以透過 element.style 取得。
var element = document.getElementById('div1');
console.log(element.style.background);
這種方式只適用於行間樣式,無法取得外部樣式表或內部樣式表中套用的值。
若要取得元素最終套用的樣式,可以使用 window.getComputedStyle。這個方法會回傳計算後的樣式。
var style = window.getComputedStyle
? window.getComputedStyle(element, null).background
: element.currentStyle.background;
console.log(style);
第二個參數通常用於偽元素,若不需要可傳入 null。較舊版本的 IE 使用 currentStyle,因此實務上常會做相容判斷。
若要直接讀取外部樣式表中的規則,可以透過 document.styleSheets 取得樣式表物件,再從 cssRules 中取出規則。
var sheet = document.styleSheets[0];
var rule = sheet.cssRules[0];
console.log(rule.style.background);
需要注意的是,若樣式表來自不同網域,瀏覽器基於安全性限制,可能無法讀取其内容。
行間樣式適合讀取直接設定的值;getComputedStyle 適合取得最終呈現的樣式;外部樣式表則適合需要遍歷或分析 CSS 規則的情境。實際開發中,若只是要確認元素目前樣式,通常優先使用 getComputedStyle。