Javascript 现代浏览器中的鼠标滚轮事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14926366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:20:58  来源:igfitidea点击:

Mousewheel event in modern browsers

javascriptmousewheel

提问by Jan Turoň

I'd like to have clean and nice JavaScript for mousewheel event, supporting only the latest version of common browsers without legacy code for obsolete versions, without any JS framework.

我想为鼠标滚轮事件使用干净漂亮的 JavaScript,只支持最新版本的常见浏览器,没有过时版本的遗留代码,没有任何 JS 框架。

Mousewheel event is nicely explained here. How to simplify it for the current latest versions of the browsers?

鼠标滚轮事件在这里得到了很好的解释。如何为当前最新版本的浏览器简化它?

I don't have access to all browsers to test it, so caniuse.comis a great help to me. Alas, mousewheel is not mentioned there.

我无法访问所有浏览器来测试它,所以caniuse.com对我有很大帮助。唉,那里没有提到鼠标滚轮。

Based on Derek's comment, I wrote this solution. Is it valid for all browsers?

根据德里克的评论,我写了这个解决方案。它对所有浏览器都有效吗?

someObject.addEventListener("onwheel" in document ? "wheel" : "mousewheel", function(e) {
  e.wheel = e.deltaY ? -e.deltaY : e.wheelDelta/40;
  // custom code
});

采纳答案by Lucio Paiva

Clean and simple:

干净简单:

window.addEventListener("wheel", event => console.info(event.deltaY));

Browsers may return different values for the delta (for instance, Chrome returns +120(scroll up) or -120(scroll down). A nice trick to normalize it is to extract its sign, effectively converting it to +1/-1:

浏览器可能会返回不同的 delta 值(例如,Chrome 返回+120(向上滚动)或-120(向下滚动)。标准化它的一个好技巧是提取其符号,有效地将其转换为+1/ -1

window.addEventListener("wheel", event => {
    const delta = Math.sign(event.deltaY);
    console.info(delta);
});

Reference: MDN.

参考:MDN

回答by Almo

Here's an article that describes this, and gives an example:

这是一篇描述这一点的文章,并给出了一个例子:

http://www.sitepoint.com/html5-javascript-mouse-wheel/

http://www.sitepoint.com/html5-javascript-mouse-wheel/

Relevant code, minus the specific example given of resizing an image:

相关代码,减去给出的调整图像大小的具体示例:

var myitem = document.getElementById("myItem");
if (myitem.addEventListener)
{
    // IE9, Chrome, Safari, Opera
    myitem.addEventListener("mousewheel", MouseWheelHandler, false);
    // Firefox
    myitem.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else
{
    myitem.attachEvent("onmousewheel", MouseWheelHandler);
}

function MouseWheelHandler(e)
{
    // cross-browser wheel delta
    var e = window.event || e; // old IE support
    var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));

    return false;
}

回答by Iter Ator

This will work in Firefox, Chrome and Edge too:

这也适用于 Firefox、Chrome 和 Edge:

window.addEventListener("wheel", function(e) {
    var dir = Math.sign(e.deltaY);
    console.log(dir);
});