如何为wheel事件添加延迟,避免触控板滚动多次触发?
解决触控板滚动时多次触发索引变更的问题
我编写了一段代码,通过鼠标滚轮或触控板切换sections数组中的下一个div视图,但使用触控板时,每次滚动都会多次改变索引,导致功能异常。请问如何添加延迟,将每次滚轮/触控板操作视为一次滚动?
const MainNavigation = () => { let index = 0; window.addEventListener("wheel", function (event) { if (event.deltaY < 0) { --index; } else if (event.deltaY > 0) { ++index; } scrollToSection(); }); const scrollToSection = () => { if (index < 0 || index > 2) { index = 0; } console.log(index); sections[index].scrollIntoView({ behavior: "smooth" }); }; };
解决方案:使用防抖(Debounce)机制
问题根源是触控板滚动会连续触发多次wheel事件,导致索引被频繁修改。通过添加防抖延迟,我们可以把短时间内的多次滚动事件合并成一次处理,确保每次滚动操作只触发一次索引变更和视图切换。
修改后的代码如下:
const MainNavigation = () => { let index = 0; let scrollTimer = null; // 存储防抖定时器ID window.addEventListener("wheel", function (event) { // 清除之前的定时器,避免连续触发多次滚动逻辑 clearTimeout(scrollTimer); // 设置延迟定时器,300ms后执行滚动处理(可根据交互感受调整延迟时长) scrollTimer = setTimeout(() => { // 根据滚动方向调整索引,同时限制索引范围 if (event.deltaY < 0) { index = Math.max(0, index - 1); // 索引最小为0,避免负数 } else if (event.deltaY > 0) { index = Math.min(sections.length - 1, index + 1); // 索引最大为sections最后一项的下标 } scrollToSection(); }, 300); }); const scrollToSection = () => { console.log(index); sections[index].scrollIntoView({ behavior: "smooth" }); }; };
关键说明
- 防抖延迟时长:300ms是比较适中的数值,你可以根据实际体验调整(比如200-500ms),平衡响应速度和防误触效果
- 索引边界优化:把原代码中索引超出范围就重置为0的逻辑,改成限制在合理范围内(0到
sections.length-1),更符合用户滚动的预期 - 定时器管理:每次触发
wheel事件时先清除之前的定时器,确保只有最后一次滚动操作会触发视图切换
内容的提问来源于stack exchange,提问作者Gagik Manasyan
相关产品推荐
相关产品推荐

