MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

滚轮事件

这篇翻译不完整。请帮忙从英语翻译这篇文章

当滚动鼠标滚轮或操作其它类似输入设备时会触发滚轮事件。滚轮事件替换了已被弃用的非标准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.deltaX Read only
Returns a double representing the horizontal scroll amount.
WheelEvent.deltaY Read only
Returns a double representing the vertical scroll amount.
WheelEvent.deltaZ Read only
Returns a double representing the scroll amount for the z-axis.
WheelEvent.deltaMode Read only
Returns an unsigned long representing the unit of the delta values scroll amount. Permitted values are:
Constant Value Description
DOM_DELTA_PIXEL 0x00 The delta values are specified in pixels.
DOM_DELTA_LINE 0x01 The delta values are specified in lines.
DOM_DELTA_PAGE 0x02 The delta values are specified in pages.

Properties of MouseEvent

This interface also inherits properties of its parents, UIEvent and Event.

MouseEvent.altKey Read only
Returns true if the alt key was down when the mouse event was fired.
MouseEvent.button Read only
The button number that was pressed when the mouse event was fired. 
MouseEvent.buttons Read only

The buttons being pressed when the mouse event was fired

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.
MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.
MouseEvent.ctrlKey Read only
Returns true if the control key was down when the mouse event was fired.
MouseEvent.metaKey Read only
Returns true if the meta key was down when the mouse event was fired.
MouseEvent.movementX Read only
The X coordinate of the mouse pointer relative to the position of the last mousemove event.
MouseEvent.movementY Read only
The Y coordinate of the mouse pointer relative to the position of the last mousemove event.
MouseEvent.offsetX Read only
The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.
MouseEvent.offsetY Read only
The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.
MouseEvent.pageX Read only
The X coordinate of the mouse pointer relative to the whole document.
MouseEvent.pageY Read only
The Y coordinate of the mouse pointer relative to the whole document.
MouseEvent.region Read only
Returns the id of the hit region affected by the event. If no hit region is affected, null is returned.
MouseEvent.relatedTarget Read only

The secondary target for the event, if there is one.

MouseEvent.screenX Read only
The X coordinate of the mouse pointer in global (screen) coordinates.
MouseEvent.screenY Read only
The Y coordinate of the mouse pointer in global (screen) coordinates.
MouseEvent.shiftKey Read only
Returns true if the shift key was down when the mouse event was fired.
MouseEvent.which Read only
The button being pressed when the mouse event was fired.
MouseEvent.mozPressure Read only
The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
MouseEvent.mozInputSource Read 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_UNKNOWN 0 The input device is unknown.
MouseEvent.MOZ_SOURCE_MOUSE 1 The event was generated by a mouse (or mouse-like device).
MouseEvent.MOZ_SOURCE_PEN 2 The event was generated by a pen on a tablet.
MouseEvent.MOZ_SOURCE_ERASER 3 The event was generated by an eraser on a tablet.
MouseEvent.MOZ_SOURCE_CURSOR 4 The event was generated by a cursor.
MouseEvent.MOZ_SOURCE_TOUCH 5 The event was generated on a touch interface.
MouseEvent.MOZ_SOURCE_KEYBOARD 6 The event was generated by a keyboard.
MouseEvent.x Read only
Alias for MouseEvent.clientX.
MouseEvent.y Read only
Alias for MouseEvent.clientY

Properties of UIEvent

This interface also inherits properties of its parent, Event.

UIEvent.cancelBubble
Is a Boolean indicating whether the bubbling of the event has been canceled or not.
UIEvent.detailRead only
Returns a long with details about the event, depending on the event type.
UIEvent.isChar Read only
Returns a Boolean indicating whether the event produced a key character or not.
UIEvent.layerX Read only
Returns the horizontal coordinate of the event relative to the current layer.
UIEvent.layerY Read only
Returns the vertical coordinate of the event relative to the current layer.
UIEvent.pageX Read only
Returns the horizontal coordinate of the event relative to the whole document.
UIEvent.pageY Read only
Returns the vertical coordinate of the event relative to the whole document.
UIEvent.viewRead only
Returns a WindowProxy that contains the view that generated the event.
UIEvent.which Read only
Returns the numeric keyCode of the key pressed, or the character code (charCode) for an alphanumeric key pressed.

Properties of Event

Event()
Creates an Event object.

Properties

This interface doesn't inherit any property.

Event.bubbles Read only
A boolean indicating whether the event bubbles up through the DOM or not.
Event.cancelable Read only
A boolean indicating whether the event is cancelable.
Event.currentTarget Read only
A reference to the currently registered target for the event.
Event.defaultPrevented Read only
Indicates whether or not event.preventDefault() has been called on the event.
Event.eventPhase Read only
Indicates which phase of the event flow is being processed.
Event.explicitOriginalTarget Read only
The explicit original target of the event (Mozilla-specific).
Event.originalTarget Read 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.target Read only
A reference to the target to which the event was originally dispatched.
Event.timeStamp Read only
The time that the event was created.
Event.type Read only
The name of the event (case-insensitive).
Event.isTrusted Read 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 MouseEvent created. 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 UIEvent object. 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.stopPropagation instead.
Event.preventCapture() Obsolete since Gecko 24
Obsolete, use event.stopPropagation instead.
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()阻止, 将什么都不会发生。

以下为事件顺序:

  1. 滚轮事件处于默认事件组 (web应用和浏览器插件都可以处理这个组的事件)
  2. 当连续滚轮事件 deltaY 的值累计大于1或小于-1时,竖直方向的 DOMMouseScroll 事件既属于默认事件组也属于系统事件组
  3. 当最近的滚轮事件的 deltaY 值非零时,两个事件组都包含竖直方向的 MozMousePixelScroll 事件
  4. 当连续滚轮事件 deltaX 的值累计大于1或小于-1时,两个事件组都包含水平方向的 DOMMouseScroll 事件
  5. 当最近的滚轮事件的 deltaX 值非零时,两个事件组都包含水平方向的 MozMousePixelScroll 事件
  6. 一个滚轮事件处于系统事件组 (只有浏览器插件可以处理这个组的事件)
各个事件调用 preventDefault() 会发生什么?
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

非用户真实操作触发的滚轮事件不会引发默认行为。

参考

文档标签和贡献者

 此页面的贡献者: lufengd3, ziyunfei
 最后编辑者: lufengd3,