【问题标题】:preventDefault() error in Chrome for mousewheel DOMMouseScrollChrome 中用于鼠标滚轮 DOMMouseScroll 的 preventDefault() 错误
【发布时间】:2019-04-27 06:24:51
【问题描述】:

我在 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
    });
})();

镀铬错误

[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See...

谢谢!

【问题讨论】:

标签: javascript jquery google-chrome


【解决方案1】:

根据错误中给出的信息,转到所述错误中链接的 URL,没有明显的方法可以用 jQuery 解决这个问题(可能是,但我不使用 jQuery,所以我说你可以't) ... 使用常规 javascript - 您可以在第三个参数中传递 {passive:false} - 修复了这个 Chrome "feature"

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}
);

正如 cmets 中提到的,一些 OLD(非常非常老的)浏览器可能不喜欢这种语法 ({passive:true|false})

所以 - 你可能想要功能检测选项 - 来自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 没有一点哭泣

【讨论】:

  • 不使用特征检测意味着脚本会在不支持supportpassive的浏览器上崩溃...
  • 你已经测试了你的小理论@Shikkediel - 或者你只是在猜测?
  • 不必粗鲁。我实际上已经进行了广泛的测试。除此之外,它在 Mozilla documentation.
  • Mozilla 工作正常,我并没有粗鲁 - 但我会在答案中添加一个链接 - 对于不更新浏览器的人来说显然很有用
  • 错位的居高临下被视为粗鲁。 IE11 是一款仍在维护的浏览器,无论出于何种原因,运行 Windows 7 的少数人可能仍在使用它。因此,在这种情况下,“旧”几乎不合适。但我非常感谢更新后的答案。
猜你喜欢
  • 2014-10-01
  • 1970-01-01
  • 2020-11-06
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
  • 2016-07-24
相关资源
最近更新 更多