[Chromium给我警告,我的事件监听器不是被动的。
精细。
我不打算在那里使用event.preventDefault()
,所以我愿意使其变为被动。
但是当我阅读detailed explanation时,该示例使用Modernizr来检查属性是否可用。
addEventListener(document, "touchstart", function(e) {
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
但是我没有安装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);