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

2020-04-25 08:01:07易采站长站整理


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) {
let run = true;

return function () {
if (!run) return;
run = false;
setTimeout(() => {
fn.apply(this, arguments);
run = true;
}, interval);
};
}

用处:减少代码执行频率✅

函数防抖

当你加了函数防抖之后:


window.addEventListener("scroll", debounce(() => console.log("滚动结束!")));

效果如下:
 

debounce
源码: