要讀取元素的樣式,最直覺的做法是 document.getElementById("div1").style.width。但這個語法只看得見行內樣式;一旦樣式是寫在 <style> 區塊或外部 link 檔案裡,就會拿到空值。
標準瀏覽器使用 window.getComputedStyle(obj, null)[property];IE 系列則改用 obj.currentStyle[property]。兩者取到的都是元素「最終生效」的樣式,而不只是標籤上寫的那些。
<!DOCTYPE html>
<html>
<head>
<title>js獲取元素外鏈樣式</title>
<style type="text/css">
p {
width: 500px;
line-height: 30px;
}
</style>
<script src="jquery/jquery-1.11.2.min.js"></script>
<script>
function getstyle(obj, property) {
if (obj.currentStyle) {
return obj.currentStyle[property];
} else if (window.getComputedStyle) {
// 也可以寫成 window.getComputedStyle(obj, null)[property]
return document.defaultView.getComputedStyle(obj, null)[property];
}
return null;
}
$(document).ready(function(){
$("p").click(function(){
alert(getstyle(this, "width"));
});
});
</script>
</head>
<body>
<p style="width:750px;">如果您點擊我,彈出寬度。</p>
<p>點擊我,彈出寬度。</p>
<p>也要點擊我。</p>
</body>
</html>
第一段 <p> 寫了行內 width:750px,點擊會得到 750px;第二、三段沒有行內樣式,點擊會得到樣式表中的 500px。這正好證明兩種來源都能被同一支函式讀到。
補充一點:document.defaultView.getComputedStyle 與 window.getComputedStyle 是同一個東西,前者在 iframe 場景下語意更明確。若連 null 都取不到樣式,通常代表屬性名稱拼錯或該屬性尚未被計算。