萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 取得元素計算樣式:跨瀏覽器相容寫法

兩大標準

  • IE:element.currentStyle
  • W3C 標準瀏覽器:window.getComputedStyle(element, pseudoElt)

行內樣式(style 屬性)可直接用 element.style.property 取得;外部樣式表則需用上述方式。

currentStyle 與 getComputedStyle 差異

  • currentStyle 反映樣式表優先順序(行內 > 樣式表 > HTML 屬性 > 瀏覽器預設)。
  • getComputedStyle 回傳最終計算值(含繼承、預設值),單位統一為絕對單位(如 px)。

通用取樣式函式

function getStyle(node, property) {
    // 1. 行內樣式
    if (node.style[property]) return node.style[property];
    // 2. IE currentStyle
    if (node.currentStyle) return node.currentStyle[property];
    // 3. W3C getComputedStyle
    if (document.defaultView && document.defaultView.getComputedStyle) {
        var style = document.defaultView.getComputedStyle(node, null);
        return style.getPropertyValue(property);
    }
    return null;
}

使用範例

var div = document.getElementById('myDiv');
console.log(getStyle(div, 'width'));      // 如 '200px'
console.log(getStyle(div, 'backgroundColor'));// 如 'rgb(255, 0, 0)'

現代補充

現代瀏覽器皆支援 getComputedStyle,IE9+ 也已支援。若專案已棄用 IE8,可直接使用標準 API;若需支援舊版 IE,保留上述判斷邏輯即可。

copyright © 萬盛學電腦網 all rights reserved