Javascript 警告:向阻止滚动的“touchstart”事件添加了非被动事件侦听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46542428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:29:30  来源:igfitidea点击:

Warning: Added non-passive event listener to a scroll-blocking 'touchstart' event

javascriptgoogle-chrome

提问by codegeek

I am getting a weird warning while opening the application in chrome.I don't know how to get rid of this warning

我在 chrome 中打开应用程序时收到一个奇怪的警告。我不知道如何摆脱这个警告

[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive.

[违规] 向阻止滚动的“鼠标滚轮”事件添加了非被动事件侦听器。考虑将事件处理程序标记为“被动”以使页面更具响应性。

any one pls help me put on this.Thanks in advance

任何人请帮我穿上这个。提前致谢

采纳答案by Martin Chaov

There is an update of the API of event listeners.

事件侦听器的 API 有更新。

In short this:

简而言之:

document.addEventListener('touchstart', handler, true);

becomes this:

变成这样:

document.addEventListener('touchstart', handler, {capture: true});

Since in your case you attach event listener to touchstart it should be like that:

由于在您的情况下您将事件侦听器附加到 touchstart 它应该是这样的:

document.addEventListener('touchstart', handler, {passive: true});

This way you can setup in advance which exact event and if the passive interface is supported:

通过这种方式,您可以提前设置确切的事件以及是否支持被动接口:

var passiveEvent = false;
try {
    var opts = Object.defineProperty({}, 'passive', {
        get: function () {
            passiveEvent = true;
        }
    });
    window.addEventListener("test", null, opts);
} catch (e) { }

// in my case I need both passive and capture set to true, change as you need it.
    passiveEvent = passiveEvent ? { capture: true, passive: true } : true;

//if you need to handle mouse wheel scroll
var supportedWheelEvent: string = "onwheel" in HTMLDivElement.prototype ? "wheel" :
    document.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll";

And use like this:

并像这样使用:

elementRef.addEventListener("touchstart", handler, passiveEvent);

More details on passive event listeners here: https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md

有关被动事件侦听器的更多详细信息,请访问:https: //github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md