讀取元素樣式時,行內樣式(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。