本文介绍了我无法阻止Chrome中的鼠标滚轮事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想防止用户通过鼠标滚轮滚动.在Firefox中有效,但在Chrome中不起作用. Chrome必须更改什么?

I want to prevent the user from scrolling via mouse wheel. In Firefox it works but not in Chrome. What must be changed for Chrome?

$(window).on('wheel', function(e) {
  e.preventDefault(); // Prevent user scroll during page jump
})

jsFiddle

推荐答案

您需要将事件处理程序设置为非被动才能在Chrome上运行.据我所知,这在jQuery中是不可能的.但是您可以为此使用常规的addEventListener.

You need to set the event handler to non-passive for it to work on Chrome. That is not possible in jQuery as far as I know. But you can use the regular addEventListener for this.

document.addEventListener('wheel', function(e) {
  e.preventDefault(); // Prevent user scroll during page jump
}, {
  passive: false
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
  height: 2000px;
}
<div id="banner-message">
  <p>Mousewheel should be prevented</p>
</div>

Shikkediel 在评论中指出:如果您要支持较旧的(版本)浏览器(例如, Internet Explorer),建议先检查浏览器是否支持passive选项.较早的浏览器将布尔类型作为addEventListener的第三个参数.因此,它们可能会引发错误,或者可以将第三个参数设置为true(默认为false),这可能会导致某些不良行为.您可以使用下面的代码.

As pointed out by Shikkediel in the comments: if you want to support older (versions of) browsers (for example Internet Explorer), it is recommended to first check if the passive option is supported by the browser. Older browsers had a boolean type as the third parameter of the addEventListener. Therefore they might throw an error, or they could set the third parameter to true (default is false) which might cause some undesired behavior. You can use the code below for that.

var passiveSupported = supportsPassive();

document.addEventListener('wheel', function(e) {
  e.preventDefault(); // Prevent user scroll during page jump
}, passiveSupported ? {
  passive: false
} : false);

function supportsPassive() {
  var passiveSupported = false;

  try {
    var options = {
      get passive() {
        passiveSupported = true;
      }
    };

    window.addEventListener("test", options, options);
    window.removeEventListener("test", options, options);
  } catch (err) {
    passiveSupported = false;
  }

  return passiveSupported;
}
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
  height: 2000px;
}
<div id="banner-message">
  <p>Mousewheel should be prevented</p>
</div>

这篇关于我无法阻止Chrome中的鼠标滚轮事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:30