JS中宽高获取

获取网页窗体方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 网页可见区域宽(可变): 
document.body.clientWidth
// 网页可见区域高(可变):
document.body.clientHeight
// 网页可见区域宽(包括边线的宽):
document.body.offsetWidth
// 网页可见区域高(包括边线的高):
document.body.offsetHeight
// 网页正文全文宽:
document.body.scrollWidth
// 网页正文全文高:
document.body.scrollHeight
// 网页被卷去的高:
document.body.scrollTop
// 网页被卷去的左:
document.body.scrollLeft

获取DOM元素的宽高

元素的实际高度:

1
document.getElementById("div").offsetHeight

元素的实际宽度:

1
document.getElementById("div").offsetWidth

元素的实际距离左边界的距离:

1
document.getElementById("div").offsetLeft

元素的实际距离上边界的距离:

1
document.getElementById("div").offsetTop

Element.getBoundingClientRect().width/height

除了能够获取宽高,还能获取元素位置等信息
MDN参考资料

1
2
console.log(ele.getBoundingClientRect().width); // 100
console.log(ele.getBoundingClientRect().height); // 100

Canvas宽高获取

canvas 元素的宽度

1
canvas.offsetWidth;

canvas 画布的宽度

1
canvas.width;

scrollWidth/clientWidth/offsetWidth的区别

scrollWidth:对象的实际内容的宽度,不包边线宽度,会随对象中内容超过可视区后而变大。
clientWidth:对象内容的可视区的宽度,不包滚动条等边线,会随对象显示大小的变化而改变。
offsetWidth:对象整体的实际宽度,包滚动条等边线,会随对象显示大小的变化而改变

获取DOM的样式

Element.style.width/height

只能获取内联样式

1
2
3
var ele = document.getElementById('element');
console.log(ele.style.width);
console.log(ele.style.height);

window.getComputedStyle(ele).width/height

可获取实际生效的样式

获取的宽度可能是80%这样的值

MDN参考资料

1
2
console.log(window.getComputedStyle(ele).width); // '100px'
console.log(window.getComputedStyle(ele).height); // '100px'

Element.currentStyle.width/height

功能与getComputedStyle相同,只存在于旧版本IE中(IE9以下),除了做旧版IE兼容,就不要用它了。