獲取當前對象的樣式DOM標准中的全局方法 getComputedStyle(obj).width (獲取元素的寬度),但在非標准IE瀏覽器(IE8)以下有兼容問題
IE8以下要這樣寫 obj.currentStyle.width 這樣的話在IE8以下正常顯示,但標准瀏覽器下又會報錯,所以一要判斷一下
//getStyle()函數,獲取元素的非行內樣式 //使用方法 getStyle(元素,"屬性名") 如:getStyle(oBox,"background")
function getStyle(obj,attr) { if(window.getComputedStyle){//瀏覽器如果支持getComputedStyle()方法
return getComputedStyle(obj)[attr]; }else{ return obj.currentStyle[attr]; } }
obj.style.width只能獲取行內元素樣式
<head>
<style> .block{ width: 100px; height: 100px;
}
</style>
</head>
<body>
<div class="block" style="background:blueviolet;"></div>
<script>
var block = document.getElementsByClassName("block")[0]; console.log(block.style.width);//什么都不輸出
console.log(block.style.background);//blueviolet
</script>
</body>
</html>