警告:为滚动阻止"touchstart"事件添加了非被动事件侦听器

cod*_*eek 13 javascript google-chrome

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

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

任何人都帮我把这件事说出来.谢谢你

Mar*_*aov 9

有一个事件监听器API的更新.

简而言之:

document.addEventListener('touchstart', handler, true);
Run Code Online (Sandbox Code Playgroud)

成为这个:

document.addEventListener('touchstart', handler, {capture: true});
Run Code Online (Sandbox Code Playgroud)

因为在您的情况下,您将事件监听器附加到touchstart,它应该是这样的:

document.addEventListener('touchstart', handler, {passive: true});
Run Code Online (Sandbox Code Playgroud)

这样,您可以提前设置哪个确切事件以及是否支持被动接口:

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";
Run Code Online (Sandbox Code Playgroud)

并使用这样的:

elementRef.addEventListener("touchstart", handler, passiveEvent);
Run Code Online (Sandbox Code Playgroud)

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