滚动混淆属性解析
elem.clientWidth/clientHeight:是元素宽高(包含内容+内边距)
elem.offsetWidth/offsetHeight:是元素宽高(包含内容+内边距+边框)
elem.offsetTop: 是获取元素elem元素到网页顶部的距离
scrollTop: 网页滚出手机顶端之后,网页的顶部,距离手机顶部的距离
document.documentElement.scrollTop: 获取/设置的是整个网页滚出窗口的距离;也就是滚出的网页顶部距离窗口顶部的距离
document.documentElement.offsetHeight: 获取的是整个网页文档的高度
滚动分类
全局滚动
// 可以设置滚动条滚动
window.scrollTo(x, y);
// 可以设置滚动条使得页面在y轴上滚动,也就是页面向上滚动500
// 设置之后立即滚动,等价于设置document.documentElement.scrollTop = 500
window.scrollTo(0, 500)
// or
window.scrollTo({
left: 0,
top: 100
});
局部滚动
指定某一元素滚动到某个位置:先获取元素到整个文档顶部的距离,然后再设置全局滚动条进行滚动
// 获取元素的offsetTop(元素距离文档顶部的距离)
let offsetTop = document.querySelector(".box").offsetTop;
// 设置滚动条的高度
window.scrollTo(0, offsetTop);
scrollingElement
滚动优化
滚动防抖
滚动节流
干货补充
滚动到底部
window.scrollTo({
left: 0,
top: document.scrollingElement.scrollHeight
});
// 如果你实在是懒的话...
window.scrollTo(0, 999999);
判断滚动到底部
window.addEventListener("scroll", () => {
let {
scrollTop,
scrollHeight,
clientHeight
} = document.scrollingElement;
// 当前滚动高度 + 视口高度 >= 文档总高度
if (scrollTop + clientHeight >= scrollHeight) {
console.log("已到达底部");
}
});
元素有定位时获取距离文档的高度
如果元素有定位,或者父元素有定位时,注意此时如果获取元素到文档顶部的距离,需要递归向上加