当滚动鼠标滚轮或操作其它类似输入设备时会触发滚轮事件。滚轮事件替换了已被弃用的非标准mousewheel事件。
概要
- 接口
WheelEvent- 同步性
- 异步
- 事件冒泡
- 是
- 可取消
- 是
- 目标元素
- defaultView, Document, Element
- 默认行为
- 滚动, 历史记录切换, 或者放大/缩小.
属性
滚轮事件实现了以下事件的属性: WheelEvent, MouseEvent, UIEvent and Event.
Properties of WheelEvent
This interface inherits properties from its parents, MouseEvent, UIEvent and Event.
WheelEvent.deltaXRead only- Returns a
doublerepresenting the horizontal scroll amount. WheelEvent.deltaYRead only- Returns a
doublerepresenting the vertical scroll amount. WheelEvent.deltaZRead only- Returns a
doublerepresenting the scroll amount for the z-axis. WheelEvent.deltaModeRead only- Returns an
unsigned longrepresenting the unit of the delta values scroll amount. Permitted values are:Constant Value Description DOM_DELTA_PIXEL0x00The delta values are specified in pixels. DOM_DELTA_LINE0x01The delta values are specified in lines. DOM_DELTA_PAGE0x02The delta values are specified in pages.
Properties of MouseEvent
This interface also inherits properties of its parents, UIEvent and Event.
MouseEvent.altKeyRead only- Returns
trueif the alt key was down when the mouse event was fired. MouseEvent.buttonRead only- The button number that was pressed when the mouse event was fired.
MouseEvent.buttonsRead only-
The buttons being pressed when the mouse event was fired
MouseEvent.clientXRead only- The X coordinate of the mouse pointer in local (DOM content) coordinates.
MouseEvent.clientYRead only- The Y coordinate of the mouse pointer in local (DOM content) coordinates.
MouseEvent.ctrlKeyRead only- Returns
trueif the control key was down when the mouse event was fired. MouseEvent.metaKeyRead only- Returns
trueif the meta key was down when the mouse event was fired. MouseEvent.movementXRead only- The X coordinate of the mouse pointer relative to the position of the last
mousemoveevent. MouseEvent.movementYRead only- The Y coordinate of the mouse pointer relative to the position of the last
mousemoveevent. MouseEvent.offsetXRead only- The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.
MouseEvent.offsetYRead only- The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.
MouseEvent.pageXRead only- The X coordinate of the mouse pointer relative to the whole document.
MouseEvent.pageYRead only- The Y coordinate of the mouse pointer relative to the whole document.
MouseEvent.regionRead only- Returns the id of the hit region affected by the event. If no hit region is affected,
nullis returned. MouseEvent.relatedTargetRead only-
The secondary target for the event, if there is one.
MouseEvent.screenXRead only- The X coordinate of the mouse pointer in global (screen) coordinates.
MouseEvent.screenYRead only- The Y coordinate of the mouse pointer in global (screen) coordinates.
MouseEvent.shiftKeyRead only- Returns
trueif the shift key was down when the mouse event was fired. MouseEvent.whichRead only- The button being pressed when the mouse event was fired.
MouseEvent.mozPressureRead only- The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between
0.0(minimum pressure) and1.0(maximum pressure). MouseEvent.mozInputSourceRead only-
The type of device that generated the event (one of the
MOZ_SOURCE_*constants listed below). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). The possible values are:Constant name Value Desription MouseEvent.MOZ_SOURCE_UNKNOWN0 The input device is unknown. MouseEvent.MOZ_SOURCE_MOUSE1 The event was generated by a mouse (or mouse-like device). MouseEvent.MOZ_SOURCE_PEN2 The event was generated by a pen on a tablet. MouseEvent.MOZ_SOURCE_ERASER3 The event was generated by an eraser on a tablet. MouseEvent.MOZ_SOURCE_CURSOR4 The event was generated by a cursor. MouseEvent.MOZ_SOURCE_TOUCH5 The event was generated on a touch interface. MouseEvent.MOZ_SOURCE_KEYBOARD6 The event was generated by a keyboard. MouseEvent.xRead only- Alias for
MouseEvent.clientX. MouseEvent.yRead only- Alias for
MouseEvent.clientY
Properties of UIEvent
This interface also inherits properties of its parent, Event.
UIEvent.cancelBubble- Is a
Booleanindicating whether the bubbling of the event has been canceled or not.
UIEvent.detailRead only- Returns a
longwith details about the event, depending on the event type. UIEvent.isCharRead only- Returns a
Booleanindicating whether the event produced a key character or not. UIEvent.layerXRead only- Returns the horizontal coordinate of the event relative to the current layer.
UIEvent.layerYRead only- Returns the vertical coordinate of the event relative to the current layer.
UIEvent.pageXRead only- Returns the horizontal coordinate of the event relative to the whole document.
UIEvent.pageYRead only- Returns the vertical coordinate of the event relative to the whole document.
UIEvent.viewRead only- Returns a
WindowProxythat contains the view that generated the event. UIEvent.whichRead only- Returns the numeric
keyCodeof the key pressed, or the character code (charCode) for an alphanumeric key pressed.
Properties of Event
Event()- Creates an
Eventobject.
Properties
This interface doesn't inherit any property.
Event.bubblesRead only- A boolean indicating whether the event bubbles up through the DOM or not.
Event.cancelableRead only- A boolean indicating whether the event is cancelable.
Event.currentTargetRead only- A reference to the currently registered target for the event.
Event.defaultPreventedRead only- Indicates whether or not
event.preventDefault()has been called on the event. Event.eventPhaseRead only- Indicates which phase of the event flow is being processed.
Event.explicitOriginalTargetRead only- The explicit original target of the event (Mozilla-specific).
Event.originalTargetRead only- The original target of the event, before any retargetings (Mozilla-specific).
Event.srcElement- A nonstandard alias for
Event.target. (old Internet Explorer-specific) Event.targetRead only- A reference to the target to which the event was originally dispatched.
Event.timeStampRead only- The time that the event was created.
Event.typeRead only- The name of the event (case-insensitive).
Event.isTrustedRead only- Indicates whether or not the event was initiated by the browser (after a user click for instance) or by a script (using an event creation method, like event.initEvent)
方法
滚轮事件实现了以下事件的方法: WheelEvent, MouseEvent, UIEvent and Event.
Methods of WheelEvent
This interface doesn't define any methods, but inherits methods from its parents, MouseEvent, UIEvent and Event.
Methods of MouseEvent
This interface also inherits methods of its parents, UIEvent and Event.
MouseEvent.getModifierState()- Returns the current state of the specified modifier key. See the
KeyboardEvent.getModifierState() for details. MouseEvent.initMouseEvent()- Initializes the value of a
MouseEventcreated. If the event has already being dispatched, this method does nothing.
Methods of UIEvent
This interface also inherits methods of its parent, Event.
UIEvent.initUIEvent()- Initializes a
UIEventobject. If the event has already being dispatched, this method does nothing.
Methods of Event
This interface doesn't inherit any method.
Event.initEvent()- Initializes the value of an Event created. If the event has already being dispatched, this method does nothing.
Event.preventBubble()Obsolete since Gecko 24- Prevents the event from bubbling. Obsolete, use
event.stopPropagationinstead. Event.preventCapture()Obsolete since Gecko 24- Obsolete, use
event.stopPropagationinstead. Event.preventDefault()- Cancels the event (if it is cancelable).
Event.stopImmediatePropagation()- For this particular event, no other listener will be called. Neither those attached on the same element, nor those attached on elements which will be traversed later (in capture phase, for instance)
Event.stopPropagation()- Stops the propagation of events further along in the DOM.
Event.getPreventDefault()- ?
规范
| Specification | Status | Comment |
|---|---|---|
| Document Object Model (DOM) Level 3 Events Specification wheel |
Working Draft | Initial definition. |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 31 | 17.0 (17.0) | 9.0[1] | 未实现 | 7.0.5 |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | 17.0 (17.0) | ? | ? | ? |
[1] IE只能通过 addEventListener 绑定滚动事件,DOM对象上没有onwheel属性. Bug report.
跨浏览器监听滚动事件
以下脚本创建了一个全局的 addWheelListener 方法,它可以兼容各浏览器监听滚动事件,并且阻止默认行为。
// creates a global "addWheelListener" method
// example: addWheelListener( elem, function( e ) { console.log( e.deltaY ); e.preventDefault(); } );
(function(window,document) {
var prefix = "", _addEventListener, onwheel, support;
// detect event model
if ( window.addEventListener ) {
_addEventListener = "addEventListener";
} else {
_addEventListener = "attachEvent";
prefix = "on";
}
// detect available wheel event
support = "onwheel" in document.createElement("div") ? "wheel" : // 各个厂商的高版本浏览器都支持"wheel"
document.onmousewheel !== undefined ? "mousewheel" : // Webkit 和 IE一定支持"mousewheel"
"DOMMouseScroll"; // 低版本firefox
window.addWheelListener = function( elem, callback, useCapture ) {
_addWheelListener( elem, support, callback, useCapture );
// handle MozMousePixelScroll in older Firefox
if( support == "DOMMouseScroll" ) {
_addWheelListener( elem, "MozMousePixelScroll", callback, useCapture );
}
};
function _addWheelListener( elem, eventName, callback, useCapture ) {
elem[ _addEventListener ]( prefix + eventName, support == "wheel" ? callback : function( originalEvent ) {
!originalEvent && ( originalEvent = window.event );
// create a normalized event object
var event = {
// keep a ref to the original event object
originalEvent: originalEvent,
target: originalEvent.target || originalEvent.srcElement,
type: "wheel",
deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1,
deltaX: 0,
deltaZ: 0,
preventDefault: function() {
originalEvent.preventDefault ?
originalEvent.preventDefault() :
originalEvent.returnValue = false;
}
};
// calculate deltaY (and deltaX) according to the event
if ( support == "mousewheel" ) {
event.deltaY = - 1/40 * originalEvent.wheelDelta;
// Webkit also support wheelDeltaX
originalEvent.wheelDeltaX && ( event.deltaX = - 1/40 * originalEvent.wheelDeltaX );
} else {
event.deltaY = originalEvent.detail;
}
// it's time to fire the callback
return callback( event );
}, useCapture || false );
}
})(window,document);
Gecko notes
滚轮事件和其它的鼠标滚动事件
如果一个用户真实操作触发的滚轮事件没有被处理, 这会触发一个 DOMMouseScroll 事件和一个 MozMousePixelScroll 事件以向下兼容. 它们的属性值由滚轮事件delta值和最近的ancestor clipped元素计算出。(i.e., overflow 不可见). 如果滚轮事件或其它任意一个剩余事件被 event.preventDefault()阻止, 将什么都不会发生。
以下为事件顺序:
- 滚轮事件处于默认事件组 (web应用和浏览器插件都可以处理这个组的事件)
- 当连续滚轮事件 deltaY 的值累计大于1或小于-1时,
竖直方向的 DOMMouseScroll事件既属于默认事件组也属于系统事件组 - 当最近的滚轮事件的 deltaY 值非零时,两个事件组都包含竖直方向的 MozMousePixelScroll 事件
- 当连续滚轮事件 deltaX 的值累计大于1或小于-1时,两个事件组都包含水平
方向的 DOMMouseScroll事件 - 当最近的滚轮事件的 deltaX 值非零时,两个事件组都包含水平方向的 MozMousePixelScroll 事件
- 一个滚轮事件处于系统事件组 (只有浏览器插件可以处理这个组的事件)
wheel (default event group) |
preventDefault() called |
||||
|---|---|---|---|---|---|
DOMMouseScroll (Vertical) |
Not fired | preventDefault() called |
|||
MozMousePixelScroll (Vertical) |
Not fired | defaultPrevented is true |
preventDefault() called |
||
DOMMouseScroll (Horizontal) |
Not fired | Not affected | Not affected | preventDefault() called |
|
MozMousePixelScroll (Horizontal) |
Not fired | Not affected | Not affected | defaultPrevented is true |
preventDefault() called |
wheel (system event group) |
defaultPrevented is true |
defaultPrevented is true |
defaultPrevented is true |
defaultPrevented is true |
defaultPrevented is true |
如果一个浏览器插件需要知道剩余事件是否被web内容所处理,它可以使用第6个滚轮事件判断,详细内容请查阅系统事件组 nsIEventListenerService 的文档。
通过设置用户偏好可以修改delta值和默认行为 (details), 因此开发者不应该期望在处理这个事件后发生特殊的行为。
delta 值
delta 值并不代表默认情况下的实际滚动值,如果用户在滚动滚轮时按住其他键,可能会产生其他行为,比如在浏览记录中前进/回退,或者放大/缩小网页内容。 此外,滚动过程中被滚动的元素不一定是目标元素,滚轮事件的目标元素是由事件触发时光标所在位置计算出的。 That event may not only not be the one actually being scrolled, 甚至都不可滚动。
deltaMode 值
在 Windows 下, 以下三个原生事件造成了 DOM 滚轮事件。
- WM_MOUSEWHEEL (竖直方向的滚动事件)
deltaMode值可以是DOM_DELTA_LINE或DOM_DELTA_PAGE。它取决于 Windows 的用户设置 (默认设置为DOM_DELTA_LINE)。- WM_MOUSEHWHEEL (水平方向的滚动事件)
deltaMode值可以是DOM_DELTA_LINE或DOM_DELTA_PAGE。然而Windows 的滚轮速度设置界面和鼠标驱动工具都没有提供改为 page scroll 的选项。 所以这个值通常为DOM_DELTA_LINE.- WM_GESTURE (Only when caused by panning)
deltaMode值总是DOM_DELTA_PIXEL。但请注意大多数笔记本的触摸板都在模拟鼠标滚轮事件而不是调用这个事件, WM_GESTURE 事件通常被平板电脑使用。
在 Mac 下 deltaMode 值由设备决定. 如果设备支持高分辨率像素级滚动, deltaMode 值就是典型的 DOM_DELTA_PIXEL. 然而用户可以通过加前缀"mousewheel.enable_pixel_scrolling"将其改变为 DOM_DELTA_LINE 。如果设备不支持高分辨率滚动,那么 deltaModel 值将一直为 DOM_DELTA_LINE.
在其它平台下, deltaMode 值总是 DOM_DELTA_LINE.
Untrusted events
非用户真实操作触发的滚轮事件不会引发默认行为。
参考
WheelEvent- Gecko's legacy events:
DOMMouseScrollandMozMousePixelScroll - Non-Gecko browsers' legacy event:
mousewheel - WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=94081