獲取元素的樣式屬性

document.getElementById("test").style.color 這種方式獲取的只是內聯樣式,並不能獲取內部樣式和外部樣式,下面爲內部樣式javascript

<div id = "test" style = "width:600px; height:300px;background-color:pink;"></div>
<script type = "text/javascript">
 window.onload = function(){
    var test = document.getElementById("test");
    var tag = document.getElementById("tag");
    console.log(getStyle(test,"width"));
	function getStyle(element, attr) {
    if(element.currentStyle) {
        return element.currentStyle[attr];
    } else {
        return window.getComputedStyle(element, null)[attr];
    }
}
 
   // console.log(test.currentStyle[width]);//不識別此句話
   // console.log(window.getComputedStyle(test).width); //500px;
   // console.log(window.getComputedStyle(test)['width']);//500px;
    
  }

</script>

上面的寬度"width"必定要加引號java

相關文章
相關標籤/搜索