-->

Bubbling scroll/mousewheel event

2019-04-16 16:39发布

问题:

I've setup my app/website such that I have an absolute-positioned canvas element on top of a scrollpanel, when the scrollpanel scrolls I apply on offset to the canvas to make it look like the image is scrolling (this allows me to have huge canvas without the overhead of a huge canvas element). The problem is, when my mouse is over the canvas element, the scroll wheel does not work, since the scroll event does not bubble. In this case, however, I need the bubbling to get the scrollbar to work.

I'm using GWT for this, so I'd prefer not to rely on a jQuery solution (although a pure javascript solution would be ok) since it's kinda hard to mix the two. I can capture the mousewheel event, but the main problem with that is that it doesn't seem to differentiate between scrolling (up/down) and tilting of the wheel (left/right). I tried eventGetShiftKey(), eventGetButton(), eventGetType(), and some others but all those methods return the same exact result for scrolling and tilting (tilt left = scroll up, tilt right = scroll down).

It seems like the best way to handle this is to bubble the actual event to the scrollpanel (which by the way also contains the parent div that contains the absolute-positioned canvas), but I'm not sure if that's possible?

回答1:

Mousewheel event does bubble, to differentiate between up/down scrolling use the event.wheelDelta and event.detail attributes.

  • MSDN: onmousewheel Event (IE, WebKit)

event.wheelDelta indicates the distance that the wheel button has rotated, expressed in multiples of 120. A positive value indicates that the wheel button has rotated away from the user. A negative value indicates that the wheel button has rotated toward the user.

  • MDC: DOMMouseScroll (Gecko)

event.detail specifies the number of "ticks" that the mouse wheel moved. Positive values mean down/right", negative up/left.
event.axis specifies the axis of the scroll gesture (horizontal or vertical). This attribute was added in Firefox 3.5

Also see this article which talks a bit about normalizing.