Capturing Scroll Wheel Events

前端 未结 3 1366
再見小時候
再見小時候 2020-12-17 02:14

I want to capture an event when a user scrolls their scroll wheel in a situation where the page does not scroll/is not scrollable. However, the standard JS scroll event only

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 02:32

    At this time, Firefox define DOMMouseScroll and wheel events. Chrome, Opera and IE (latest, again!) define mousewheel.

    This is how I did it:

    if(window.onwheel !== undefined) {
        window.addEventListener('wheel', onMouseWheel)
    } else if(window.onmousewheel !== undefined) {
        window.addEventListener('mousewheel', onMouseWheel)
    } else {
        // unsupported browser
    }
    

    Note that addEventListener support in older IE versions needs a polyfill. Alternatively you can use the old window.mousewheel = function(){} or whatever method.

    As you can see, the event listener is attached to the window object. You can't attach it to elements, in a cross-browser fashion. You can use the event object target property to see where it was triggered, and do a filter on that basis.

    PS: One more cross-browser consideration: In IE, you have to use the "wheelDelta" property (and invert it's sign!) inside the event object when processing it in the callback function ("onMouseWheel"). Other browsers will populate "deltaY" (or "deltaX" for horizontal scrolling).

提交回复
热议问题