我在 Chrome 控制台中收到此 preventDefault()
错误。我遇到了这个blog article并尝试了一些添加 { Passive: false }
但没有运气。我该如何解决这个问题?
我还读到建议使用return false;
。但我不确定这是否是我的情况的解决方案。所以我正在寻求你的建议。
$(document).on('wheel mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200)
//some code
});
})();
Chrome 错误
[干预] 由于目标被视为被动,因此无法阻止被动事件监听器内的默认行为。参见...
谢谢!
最佳答案
根据错误中给出的信息,转到所述错误中链接的 URL,没有明显的方法可以使用 jQuery 修复此问题(可能是,但我不使用 jQuery,所以我说你可以't) ...使用常规 javascript - 您可以在第三个参数中传递 {passive:false}
- 这修复了 Chrome “功能”
document.addEventListener('wheel', fn, {passive: false});
document.addEventListener('mousewheel', fn, {passive: false});
document.addEventListener('DOMMouseScroll', fn, {passive: false});
function fn(event) {
event.preventDefault();
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200)
//some code
}
或者,如果您希望代码更具 jQuery 风格,请创建一个辅助函数
const addListeners = (tgt, list, fn, options) => list.split(' ').forEach(e => tgt.addEventListener(e, fn, options));
然后像这样使用它
addListeners(document, 'wheel mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200)
//some code
}, {passive: false}
);
As mentioned in the comments, some OLD (very very old) browsers may not like this syntax
({passive:true|false})
So - you may want to feature detect the option - code from https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
var passiveSupported = false;
try {
var options = {
get passive() { // This function will be called when the browser
// attempts to access the passive property.
passiveSupported = true;
}
};
window.addEventListener("test", options, options);
window.removeEventListener("test", options, options);
} catch(err) {
passiveSupported = false;
}
在使用它之前,这样 Internet Explorer 就不会对此有一点提示
关于javascript - Chrome 中鼠标滚轮 DOMMouseScroll 的 PreventDefault() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55877877/