本範例示範如何以 JavaScript 取得元素的樣式值。做法與取得外部樣式類似,同樣利用 window.getComputedStyle(標準瀏覽器)與 currentStyle(IE)來相容不同環境,並封裝成 getStyle 函式,再搭配一個簡短的 $ 函式快速取得元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript 獲取內聯樣式</title>
</head>
<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>
<body>
<div id="box"></div>
</body>
</html>
<script>
function getStyle( obj , attr )
{
if ( window.getComputedStyle ) {
return getComputedStyle( obj , null )[attr];
}else{
return obj.currentStyle[attr];
}
}
function $(id){
return document.getElementById(id);
}
var box = $('box');
alert(getStyle(box , 'background-position'));
</script>
如此一來,無論元素的樣式是寫在行內、內部樣式表還是外部樣式表,都能正確讀取其計算後的實際值。