wheel event PreventDefault 不会取消 wheel 事件

wheel event PreventDefault does not cancel wheel event

我希望每个滚动事件只获得一个事件

我尝试了这段代码,但它产生了 "wheel" 轮子事件被触发的次数。 有什么帮助吗?谢谢

window.addEventListener("wheel",
    (e)=> {
        console.log("wheel");
        e.preventDefault();
    },
    {passive:false}
    );

用例(编辑) 我只想允许从一个页面滚动到另一个页面 - 滚动时使用动画。一旦我检测到 onwheel 事件,我想在动画结束之前停止它,否则之前的 onwheel 继续触发并且它被视为新事件,所以转到目标页面的下一个

我的结论: 无法取消车轮事件。为了在滚轮事件(来自以前的用户操作)正在进行时识别新的用户滚轮操作,我们需要计算此类事件的 speed/acceleration

您可以设置在将其他滚动事件视为可操作之前必须经过的最短时间。

例如,在再次触发 console.log("wheel") 之前,滚动事件之间必须经过 3 秒:

function createScrollEventHandler(milliseconds)
{
  let allowed = true;
  return (event)=>
  {
        event.preventDefault();
        if (allowed)
        {
          console.log("wheel");
          allowed = false;
          setTimeout(()=>
          {
            allowed = true;
          },milliseconds);
        }  
  }
}
let scrollEventHandler = createScrollEventHandler(3000); // 3 seconds
window.addEventListener("wheel",scrollEventHandler);

您几乎已经掌握了但是您需要将您的代码包装在一个函数中。 我添加了一些额外的小部分,以便您可以区分上下 :)

//scroll wheel manipulation
  window.addEventListener('wheel', function (e) {
    //TODO add delay
    if (e.deltaY < 0) {
      //scroll wheel up
      console.log("up");
    }
    if (e.deltaY > 0) {
      //scroll wheel down
      console.log("down");
    }
  });

How it works?

(e) = 这只是事件,当你上下滚动时会触发函数,但如果没有函数事件,它就不知道该做什么做!通常人们会放“事件”,但我很懒。

deltaY = 这是滚轮滚动的功能,它只是确保您沿 Y 轴滚动。它是一个标准的内置函数,您不需要添加任何外部变量。

Extras

setTimeout

你可以添加这个。在@Lonnie Best 建议的 if 语句中

这是一个相当简单的问题,将最后一个方向存储在任何地方并有条件地执行您的代码:

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 上下文。 可能 throttlingdebouncing 你的函数在某些情况下会给出更好的结果。

节流

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>