先來看一段demo
<style>
div{
position:absolute;
left: 10px;
background: red;
width: 100px;
height: 100px;
}
</style>
<script>
window.onload = function () {
var oDiv = document.getElementsByTagName("div")[0];
alert(oDiv.style.left);
}
</script>
<body>
<div></div>
</body>
FF下的顯示效果
會發現 明明在css樣式中設置了left屬性 但是獲取到的值為空
解決方案:
①將css的left屬性改到行間樣式中,即HTML內
<body>
<div style="left:10px"></div>
</body>
會發現是可以直接獲取到left屬性的值的
②可以使用currentStyle(IE Opera) getComputedStyle(FF Chrome)來獲取到我們想要的屬性值
<script> window.onload = function () { var oDiv = document.getElementsByTagName("div")[0]; alert(getStyle(oDiv,'left')); }; function getStyle(obj,attr) { if(typeof getComputedStyle) return getComputedStyle(obj,null)[attr]; else return obj.currentStyle[attr]; } </script>
最后來說一下問題的原因所在:
obj.style獲取的是DOM元素CSS樣式的聲明對象簡值。obj.style可讀可寫,所以我們會發現這樣一個問題,當我們在JS代碼中沒有寫obj.style之前去讀obj.style也就是上面所發生的情況,會彈出一個空值,style只能獲取到內聯樣式的具體值,而內部和外部樣式無法獲取到具體值。所以如果要獲取CSS對象屬性值,請使用currentStyle和getComputedStyle,但是currentStyle和getComputedStyle是只讀的,所以修改CSS樣式還是要用style來修改。
