DIV CSS 佈局教程網

JavaScript 取得元素樣式:getComputedStyle 與 currentStyle 相容寫法
編輯:關於JavaScript     

讀取元素樣式時,行內樣式(element.style)只涵蓋 style="" 屬性裡的宣告;如果是寫在 <style> 區塊或外部樣式檔中的規則,就必須改用「計算後樣式」的 API。以下用一個簡單的方塊範例,示範如何寫出同時相容標準瀏覽器與舊版 IE 的取樣式函式。

頁面結構與樣式

先準備一個 #box 方塊,樣式全部寫在 <style> 區塊中,刻意不放任何行內樣式,才能驗證函式確實讀到了外部規則。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0, user-scalable=no"/>
<title>javascript 獲取內聯樣式</title>

<style>
#box{
  width:100px;
  height:100px;
  background-image:url(1.jpg);
  background-size:140% 140%;
  background-repeat:no-repeat;
  border:20px solid rgba(0,0,0,.3);
  background-clip:border-box;
  background-position:-20px -20px;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
</html>

取樣式函式

核心只有一個函式:先判斷瀏覽器是否支援 window.getComputedStyle,支援就走標準路徑,不支援則退回 IE 的 currentStyle。

<script>
// 獲取元素樣式
function getStyle( obj , attr )
{
  if ( window.getComputedStyle ) {
    return getComputedStyle( obj , null )[attr];
  }else{
    return obj.currentStyle[attr];
  }
}

// 依 id 取得元素
function $(id){
  return document.getElementById(id);
}

var box = $('box');

// 印出樣式
alert(getStyle(box , 'background-position'));
</script>

把這段 script 放在 body 之後(或搭配 DOMContentLoaded)即可正常取到元素。執行後會跳出 -20px -20px,也就是樣式表中 background-position 的計算值。

幾個實務上的重點

  • 讀到的是計算值:像 width:100px 這種明確宣告會原樣回傳;但若是 auto、百分比或 em,瀏覽器多數會回傳換算後的像素值。
  • 屬性名稱寫法:駝峰式(backgroundColor)與連字號字串('background-color')在標準瀏覽器中都能讀取,建議統一風格避免混淆。
  • 唯讀特性:getComputedStyle 回傳的物件是唯讀的,要改樣式請直接設定 element.style.attr 或操作 cssText。
  • 效能考量:這個 API 會觸發樣式重算,在迴圈中頻繁呼叫可能造成 reflow。若只需讀一次,先把結果存進變數再用。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved