将Window对象上的Mouse Wheel事件更改为{passive:false}-Javascript

时间:2019-03-19 22:47:19

标签: javascript google-chrome events window mousewheel

随着Chrome [73]的最新更新,他们已经更改了被动事件侦听器与窗口对象上的鼠标滚轮一起工作的方式。基本上,这打破了许多平滑滚动插件,在Chrome浏览器中滚动时,这些插件消除了传统鼠标滚轮的默认“抖动”。

此处是chrome平台状态的更改。

https://www.chromestatus.com/features#browsers.chrome.owners%3A%20sahel%40chromium.org

...在此页面上,您将转到该页面,该页面上说默认值现在与此等效:

`window.addEventListener("wheel", func, {passive: true} );`

所以我想我需要编写一个将其更改为的函数:

`window.addEventListener("wheel", func, {passive: false} );`

https://github.com/sahel-sh/Document-level-passive-wheel-event-listeners/blob/master/Explainer.md

我想作为一个独立的功能来执行此操作,而不是遍历我试图确定执行方法和位置的所有插件代码。

谁会知道如何编写一个独立的函数来做到这一点?

我似乎什么都没做。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

尝试

const EVENTS_TO_MODIFY = ['touchstart', 'touchmove', 'touchend', 'touchcancel', 'wheel'];

const originalAddEventListener = document.addEventListener.bind();
document.addEventListener = (type, listener, options, wantsUntrusted) => {
  let modOptions = options;
  if (EVENTS_TO_MODIFY.includes(type)) {
    if (typeof options === 'boolean') {
      modOptions = {
        capture: options,
        passive: false,
      };
    } else if (typeof options === 'object') {
      modOptions = {
        ...options,
        passive: false,
      };
    }
  }

  return originalAddEventListener(type, listener, modOptions, wantsUntrusted);
};

const originalRemoveEventListener = document.removeEventListener.bind();
document.removeEventListener = (type, listener, options) => {
  let modOptions = options;
  if (EVENTS_TO_MODIFY.includes(type)) {
    if (typeof options === 'boolean') {
      modOptions = {
        capture: options,
        passive: false,
      };
    } else if (typeof options === 'object') {
      modOptions = {
        ...options,
        passive: false,
      };
    }
  }
  return originalRemoveEventListener(type, listener, modOptions);
};