DIV CSS 佈局教程網

JavaScript 讀取 CSS 屬性:currentStyle 與 getComputedStyle 的跨瀏覽器寫法
編輯:JavaScript綜合知識     

寫 JS 時想讀取某個元素實際套用的樣式,會發現 element.style 常常讀不到值。原因很簡單:style 只包含寫在 HTML 行內的樣式,外部樣式表與 <style> 區塊裡的規則都不在裡面。

正確的跨瀏覽器讀法

var getstyle = function (elementID, attribute) {
  var obj = document.getElementById(elementID);
  // 前者是 IE 專屬,後者才是標準做法
  return obj.currentStyle
    ? obj.currentStyle[attribute]
    : document.defaultView.getComputedStyle(obj, false)[attribute];
};

IE 用 currentStyle,其他瀏覽器用 defaultView.getComputedStyle()。兩者都會回傳元素「最終計算後」的樣式,包含繼承而來的值與樣式表的設定。

只能讀行內樣式的情況

document.getElementById("elementId").style.paddingLeft;

這行程式只有在 style="padding-left:10px" 直接寫在該元素的標籤上時才有值,否則回傳空字串。

三個實務眉角

屬性名稱要轉駝峰。CSS 寫 background-color,JS 讀 backgroundColor。用 getComputedStyle 時若傳入 'background-color' 這類帶中劃線的字串,部分瀏覽器能容忍,但IE 與舊版實作會失敗,建議一律轉成駝峰。

位置與尺寸可能得到 px,也可能得到 auto。getComputedStyle 對 width、height 通常會回傳像素值,但若元素未設定或處於 display:none,可能拿到 auto,需要 parseFloat 後判斷 isNaN。

computed style 是唯讀的。要改樣式請寫 element.style.xxx = value,直接改 computed style 物件不會生效。

現代寫法

var el = document.getElementById("box");
var bg = window.getComputedStyle(el).backgroundColor;   // 標準寫法
var w  = el.offsetWidth;                                 // 只要尺寸時更直接

window.getComputedStyle 是標準 API,IE 9 以後也都支援,因此 currentStyle 那個分支在新專案中已可移除。若只是要元素寬高,offsetWidth、clientWidth、getBoundingClientRect() 都比解析樣式字串來得準確且省事。

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