Element Dimension Properties
offsetWidth、clientWidth 和 scrollWidth 等元素尺寸属性的区别
问题
如何区分 offsetWidth/offsetHeight、clientWidth/clientHeight 和 scrollWidth/scrollHeight 这些元素尺寸属性?
解答
clientWidth/clientHeight
返回元素的内部宽度,包含 content + padding,不包含滚动条。
const element = document.querySelector('.box');
console.log(element.clientWidth); // content + padding
console.log(element.clientHeight); // content + padding
clientTop 返回上边框的宽度,clientLeft 返回左边框的宽度。
offsetWidth/offsetHeight
返回元素的布局宽度,包含 content + padding + border,包含滚动条。
const element = document.querySelector('.box');
console.log(element.offsetWidth); // content + padding + border
console.log(element.offsetHeight); // content + padding + border
offsetTop 返回当前元素相对于 offsetParent 元素顶部的距离,offsetLeft 返回相对于左侧的距离。
scrollWidth/scrollHeight
返回元素的完整内容宽度,包含 content + padding + 溢出内容的尺寸。
const element = document.querySelector('.box');
console.log(element.scrollWidth); // content + padding + 溢出内容
console.log(element.scrollHeight); // content + padding + 溢出内容
scrollTop 返回元素内容垂直滚动的像素数,scrollLeft 返回元素滚动条到左边的距离。
关键点
clientWidth/Height:内容区 + 内边距,不含边框和滚动条offsetWidth/Height:内容区 + 内边距 + 边框,含滚动条scrollWidth/Height:内容区 + 内边距 + 溢出内容,表示完整可滚动区域offsetTop/Left相对于offsetParent定位,scrollTop/Left表示滚动距离
目录