一般來說,元素若設定了行內樣式(如 <div id="div1" style="width:500px;">),可直接用 element.style.width 取得或設定。但若樣式是寫在外部 link 或非行內的樣式表中,就無法用這種方式讀取了。
解決之道是:在標準瀏覽器中可用 window.getComputedStyle(obj, null)[property] 取得,而在 IE 中則是透過 obj.currentStyle 取得。以下範例封裝了一個 getstyle 函數,同時相容兩種瀏覽器:
<!DOCTYPE html>
<html>
<head>
<title>js獲取元素的外鏈樣式</title>
<style type="text/css">
p { width: 500px; line-height: 30px; }
</style>
<script>
function getstyle(obj,property){
if(obj.currentStyle){
return obj.currentStyle[property];
}else if(window.getComputedStyle){
return document.defaultView.getComputedStyle(obj,null)[property];
}
return null;
}
</script>
</head>
<body>
<p style="width:750px;">如果您點擊我,彈出寬度。</p>
<p>點擊我,彈出寬度。</p>
</body>
</html>