在做前端网页开发的时候,经常会遇到要求在滚动中改变元素样式,滚动结束后恢复的需求。通常,比较容易想到两种方法:
- 使用
touchstart,touchmove和touchend事件监听 - 使用
scroll事件监听
这两种方法分别都有各自的缺点。前一种会遇到在 touchend事件发生后,页面依然在滚动的情况;后一种则不能类似touch事件依次触发 start, end。scroll事件有办法模拟start,end事件发生序列吗?
这里,可以使用一种取巧的方式实现。先看代码:
let timeoutHdr = null
window.addEventListener('scroll', () => {
// 开始滚动时执行的代码
window.clearTimeout(timeoutHdr)
timeoutHdr = window.setTimeout(() => {
// 滚动停止时执行的代码
}, 66)
})