获得宽高的各种方式
1、dom.style.width/height
<div class = "child1" id="child1" style="width: 100px;">
获取宽度:
var ele = document.getElementById('child1');
console.log(ele.style.width); //100px
这种方法只适用于内联样式,如果在 css 中设置 width 是获取不到的
2、window.getComputedStyle(dom).width/height
<div class = "child1" id="child1">
.child1 {
width: 100px;
}
获取宽度:
var ele = document.getElementById('child1');
console.log(window.getComputedStyle(ele).width); //100px
这种方法适用于任何设置 width 的方式,用于页面渲染完成后
3、dom.offsetWidth/offsetHeight
var ele = document.getElementById('child1');
console.log(ele.offsetWidth); //100(注意:此处返回的是一个数值100)
这种方式是最常用的,也是兼容性最好的
4、window.screen.width/height
获取屏幕的宽高
5、document.body.scrollWidth/scrollHeight
获取网页全文的宽高
6、document.body.clientWidth/Height
获取可见区域的宽高(不加边线)