通過JS獲取盒模型對應的寬和高,有以下幾種方法:
1. dom.style.width/height
這種方式只能取到dom元素內聯樣式所設置的寬高,也就是說如果該節點的樣式是在style標籤中或外聯的CSS文件中設置的話,通過這種方法是獲取不到dom的寬高的。
2. dom.currentStyle.width/height
這種方式獲取的是在頁面渲染完成後的結果,就是說不管是哪種方式設置的樣式,都能獲取到。
但這種方式只有IE瀏覽器支持,在其他的瀏覽器中會報錯的
3. window.getComputedStyle(dom).width/height
這種方式的原理和2是一樣的,這個可以兼容更多的瀏覽器,通用性好一些。
4. dom.getBoundingClientRect().width/height
這種方式是根據元素在視窗中的絕對位置來獲取寬高的
5.dom.offsetWidth/offsetHeight
最常用的,也是兼容最好的。這種方式獲取的寬高包含border,且不帶單位
下面是幾種方式的代碼實現
<style>
#container2{
width: 200px;
height: 200px;
border:1px solid red;
padding-top:20px;
}
</style>
<body>
<div id="container1" style="width:100px;height:100px;border:1px solid yellow;">
內聯樣式盒子
</div>
<div id="container2">非內聯樣式盒子</div>
</body>
<script>
var con1 = document.getElementById('container1');
console.log(con1.style.height); // 100px 只有內聯樣式中才能獲取到
console.log(window.getComputedStyle(con1).height); //100px
console.log(con1.offsetWidth);//102 注意沒有單位
var con2 = document.getElementById('container2');
// alert(con2.currentStyle.height); //ie中才生效,否則控制檯報錯
console.log(window.getComputedStyle(con2).height); // 200px;
console.log(con2.offsetWidth); // 202 注意沒有單位
</script>