scroll* 属性
获取元素的内容尺寸和滚动位置
属性说明
scroll* 系列属性用于获取和设置元素的滚动信息。
- scrollWidth - 内容的总宽度(包括溢出部分)
- scrollHeight - 内容的总高度(包括溢出部分)
- scrollLeft - 水平滚动位置(可读写)
- scrollTop - 垂直滚动位置(可读写)
const container = document.getElementById('container');
console.log(container.scrollWidth); // 内容总宽度
console.log(container.scrollHeight); // 内容总高度
console.log(container.scrollTop); // 当前滚动位置
// 设置滚动位置
container.scrollTop = 100;
container.scrollLeft = 50;
示例:内容尺寸和滚动
观察滚动时属性值的变化
↓ 向下滚动查看效果 ↓
目标元素
内容底部
滚动信息
scrollHeight:
0px
clientHeight:
0px
scrollTop:
0px
可滚动距离:
0px
💡 实际应用
最大滚动距离 = scrollHeight - clientHeight
这对于实现"加载更多"或判断是否滚动到底部非常有用。
总结
- scrollWidth/Height 表示内容的总尺寸(包括溢出)
- scrollLeft/Top 是可读写的,可以设置滚动位置
- 常用于实现无限滚动、回到顶部等功能
- 最大滚动距离 = scrollHeight - clientHeight