Aug*_*ger 5 javascript event-bubbling dom-events modernizr
Chromium 警告我我的事件侦听器不是被动的。
美好的。
我不会在那里使用event.preventDefault(),所以我愿意让它被动。
但是当我阅读详细说明时,该示例使用 Modernizr 来检查该属性是否可用。
addEventListener(document, "touchstart", function(e) {
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
Run Code Online (Sandbox Code Playgroud)
但是我没有安装 Modernizr,我发现为这个非常具体的用例设置它很痛苦。
所以问题是:如果我盲目地写会发生什么:
$el.addEventListener('touchstart', () => {}, {passive: true})?
在旧浏览器中?
我的猜测是该对象可能被评估为true,对吗?没有错误要上升?
{passive: true}将被评估为true应该消除 Chromium 警告,但根据您提供的链接,它可能在旧浏览器上产生“不可预见的结果”。
这种方法(也在该链接中建议)对我来说似乎很好,并且不需要任何其他库:
// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true;
}
});
window.addEventListener("testPassive", null, opts);
window.removeEventListener("testPassive", null, opts);
} catch (e) {}
// Use our detect's results. passive applied if supported, capture will be false either way.
elem.addEventListener('touchstart', fn, supportsPassive ? { passive: true } : false);
Run Code Online (Sandbox Code Playgroud)