大家都知道,用 document.getElementById('element').style.xxx 可以獲取元素的樣式信息,但它有一個明顯局限:只能讀取 DOM 元素 style 屬性裡的行間樣式,對於透過 class 屬性引用的外部樣式表,就拿不到我們想要的信息了。那麼如何獲取元素的非行間樣式(computed style)呢?
DOM 標準裡有個全域方法 getComputedStyle,可以獲取到當前物件的樣式規則信息,例如 getComputedStyle(obj,null).paddingLeft 就能取得物件的左內邊距。但IE 並不支援這個方法,它有自己的實現方式——currentStyle。不同於全域方法 getComputedStyle,currentStyle 是作為 DOM 元素屬性存在的,例如 obj.currentStyle.paddingLeft。
因此,兼容性的寫法如下:
return window.getComputedStyle ? window.getComputedStyle(obj,null).paddingLeft : obj.currentStyle.paddingLeft;
這樣就能在 IE 與 Firefox 中都正確返回物件的當前樣式信息了。
如果要獲取當前物件的顏色信息,需要注意:IE 返回的是十六進位的 '#ffffff',而 Firefox 返回的是 rgb(255,255,255),在進行顏色比對等處理時要特別留意這個格式差異。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js用currentStyle和getComputedStyle獲取css樣式</title>
<style type="text/css">
#div1{width:100px; height:100px; background:red;}
</style>
<script type="text/javascript">
function getStyle(obj, attr)
{
if(obj.currentStyle)
{
return obj.currentStyle[attr];
}
else
{
return getComputedStyle(obj,false)[attr];
}
}
window.onload = function()
{
var oDiv = document.getElementById('div1');
alert(getStyle(oDiv,'width'))
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
透過封裝一個 getStyle 函數,先判斷物件是否存在 currentStyle 屬性來區分瀏覽器,再分別採用對應的方法讀取樣式,就能優雅地實現跨瀏覽器獲取元素的非行間樣式,這是實際開發中非常實用的一個小技巧。