我想每个滚动事件只获得一个事件
我尝试了这段代码,但它会在触发轮子事件的次数下产生“轮子”。
有什么帮助吗?谢谢
window.addEventListener("wheel",
(e)=> {
console.log("wheel");
e.preventDefault();
},
{passive:false}
);
用例 (编辑)
我只想允许从一页滚动到另一页-滚动时带有动画。一旦我检测到 onwheel 事件,我想在动画结束之前停止它,否则之前的 onwheel 会继续触发并且它被视为新事件,所以转到目标页面的下一个
我的结论 :
无法取消车轮事件。为了在滚动事件(来自以前的用户操作)正在进行时识别新的用户滚动操作,我们需要计算此类事件的速度/加速度
请您参考如下方法:
这是一个相当简单的问题,将最后一个方向存储在任何地方并以代码方式执行您的代码:
direction = '';
window.addEventListener('wheel', (e) => {
if (e.deltaY < 0) {
//scroll wheel up
if(direction !== 'up'){
console.log("up");
direction = 'up';
}
}
if (e.deltaY > 0) {
//scroll wheel down
if(direction !== 'down'){
console.log("down");
direction = 'down';
}
}
});
无论如何, 应定义 UX 上下文 .
可能是在某些情况下,对函数进行节流或去抖动会产生更好的结果。
节流
Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."
去抖
Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called.
在你的情况下,也许去抖是最好的选择。
暂时锁定浏览器滚动
$('#test').on('mousewheel DOMMouseScroll wheel', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
<h1>1</h1>
<h1>2</h1>
<h1>3</h1>
<h1>4</h1>
<h1>5</h1>
<h1>6</h1>
<h1>7</h1>
<h1>8</h1>
<h1>9</h1>
<h1>10</h1>
</div>