'unable to preventDefault (...) due to target being treated as passive' 的问题 -- 实施解决方案时遇到问题

Problem with 'unable to preventDefault (...) due to target being treated as passive' -- having problem implementing the solution

我很抱歉这不完全是 'code problem',但我对编程社区有一些信心,所以无论如何我都会问。

每当我向下滚动时,我都会在开发工具中收到此错误:'Unable to preventDefault inside passive event listener due to target being treated as passive.'

我知道这是由 Google 中的更新引起的。问题是我看到了解决方案,但对如何实施它们一无所知。

(注意我没有使用jQuery)。

这是使用 preventDefault 的代码片段:

   window.addEventListener("wheel", function(event) {
      viewStart = scrolled.scrollTop;
      if (!pageJump) {
        var pageHeight = page.scrollHeight;
        var pageStopPortion = pageHeight / 2;
        var viewHeight = window.innerHeight;

        var viewEnd = viewStart + viewHeight;
        var pageStartPart = viewEnd - pageStart;
        var pageEndPart = pageStart + pageHeight - viewStart;

        var canJumpDown = pageStartPart >= 0;
        var stopJumpDown = pageStartPart > pageStopPortion;

        var canJumpUp = pageEndPart >= 0;
        var stopJumpUp = pageEndPart > pageStopPortion;

        var scrollingForward = event.deltaY > 0;
        if (
          (scrollingForward && canJumpDown && !stopJumpDown) ||
          (!scrollingForward && canJumpUp && !stopJumpUp)
        ) {
          event.preventDefault();
          scrollToPage();
        }
        false; //
      } else {
        event.preventDefault();
      }
    });

这是来自 stackoverlow 的建议解决方案: Unable to preventDefault inside passive event listener due to target being treated as passive - Chrome

我知道它建议我添加此代码:

el.addEventListener('someEvent', someFn, { passive: false });

任何人都可以指导我如何 'add' 吗? 因此,而不是实例:

event.preventDefault();

我应该使用这个代码吗? :

window.addEventListener("wheel", function(event){
...all of the code except 'event.preventDefault()'...
}, {passive: false});

还是我把一切都搞砸了?老实说,我们将不胜感激任何反馈。

除了将 someFn 替换为您的事件处理函数外,您完全按照它显示的方式进行操作:

window.addEventListener("wheel", function(event) {
   viewStart = scrolled.scrollTop;
   if (!pageJump) {
     var pageHeight = page.scrollHeight;
     var pageStopPortion = pageHeight / 2;
     var viewHeight = window.innerHeight;

     var viewEnd = viewStart + viewHeight;
     var pageStartPart = viewEnd - pageStart;
     var pageEndPart = pageStart + pageHeight - viewStart;

     var canJumpDown = pageStartPart >= 0;
     var stopJumpDown = pageStartPart > pageStopPortion;

     var canJumpUp = pageEndPart >= 0;
     var stopJumpUp = pageEndPart > pageStopPortion;

     var scrollingForward = event.deltaY > 0;
     if (
       (scrollingForward && canJumpDown && !stopJumpDown) ||
       (!scrollingForward && canJumpUp && !stopJumpUp)
     ) {
       event.preventDefault();
       scrollToPage();
     }
     false; //
   } else {
     event.preventDefault();
   }
 }, {passive: false});
//  ^^^^^^^^^^^^^^^^

旁注:该代码中第一个 if 块末尾的 false; 根本不执行任何操作。删除它即可。