解析浏览器的一些“滚动”行为鉴赏

2020-04-21 23:45:39易采站长站整理

一些有趣的东西

1. scrollingElement

该对象可以非常

兼容
地获取
scrollTop
scrollHeight
等属性,在
移动端
PC端
都屡试不爽🤞

还记得当初写这个兼容性方法:


let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

现在你只需要:


let scrollHeight = document.scrollingElement.scrollHeight;

因为在

MDN
中是这样介绍它的:

标准模式返回

documentElement
,怪异模式返回
body

2. 滚动到底部


window.scrollTo({
left: 0,
top: document.scrollingElement.scrollHeight
});

// 如果你实在是懒的话...
window.scrollTo(0, 999999);

注意:平滑滚动到

顶部
或者
底部
自己加参数或者属性即可✅

3. 判断浏览器已滚动到底部


window.addEventListener("scroll", () => {
let {
scrollTop,
scrollHeight,
clientHeight
} = document.scrollingElement;

// 当前滚动高度 + 视口高度 >= 文档总高度
if (scrollTop + clientHeight >= scrollHeight) {
console.log("已到达底部");
}
});

效果如下:
 

函数节流

当你没加函数节流:


window.addEventListener("scroll", () => console.log("我在滚我在滚!"));

效果如下:
 

当你加了函数节流之后:


window.addEventListener("scroll", throttle(() => console.log("我在滚我在滚!")));

效果如下:
 

throttle
源码:


function throttle(fn, interval = 500) {