Mousewheel event in modern browsers

2019-01-06 16:45发布

问题:

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.

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.com is a great help to me. Alas, mousewheel is not mentioned there.

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

回答1:

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

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


回答2:

This is way cleaner in 2018:

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

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:

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

Reference: MDN.



回答3:

This will work in Firefox, Chrome and Edge too:

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