События колесика мыши javascript

Колёсико мыши: «wheel» и аналоги

Несмотря на то, что колёсико мыши обычно ассоциируется с прокруткой, это совсем разные вещи.

  • При прокрутке срабатывает событие onscroll — рассмотрим его в дальнейшем. Оно произойдёт при любой прокрутке, в том числе через клавиатурy, но только на прокручиваемых элементах. Например, элемент с overflow: hidden в принципе не может сгенерировать onscroll .
  • А событие wheel является чисто «мышиным». Оно генерируется над любым элементом при передвижении колеса мыши. При этом не важно, прокручиваемый он или нет. В частности, overflow:hidden никак не препятствует обработке колеса мыши.

Кроме того, событие onscroll происходит после прокрутки, а onwheel — до прокрутки, поэтому в нём можно отменить саму прокрутку (действие браузера).

Зоопарк wheel в разных браузерах

Самые важные свойства современного события и его нестандартных аналогов:

  • wheel
    • Свойство deltaY — количество прокрученных пикселей по горизонтали и вертикали. Существуют также свойства deltaX и deltaZ для других направлений прокрутки.
    • Срабатывает, начиная с Firefox 3.5, только в Firefox. Даёт возможность отменить прокрутку и получить размер в пикселях через свойство detail , ось прокрутки в свойстве axis .
    • Существует в Firefox очень давно, отличается от предыдущего тем, что даёт в detail количество строк. Если не нужна поддержка Firefox < 3.5, то не нужно и это событие.
    • Срабатывает в браузерах, которые ещё не реализовали wheel. В свойстве wheelDelta — условный «размер прокрутки», обычно равен 120 для прокрутки вверх и -120 — вниз. Он не соответствует какому-либо конкретному количеству пикселей.

    Чтобы кросс-браузерно отловить прокрутку и, при необходимости, отменить её, можно использовать все эти события.

    if (elem.addEventListener) < if ('onwheel' in document) < // IE9+, FF17+ elem.addEventListener ("wheel", onWheel, false); > else if ('onmousewheel' in document) < // устаревший вариант события elem.addEventListener ("mousewheel", onWheel, false); > else < // 3.5 elem.addEventListener ("MozMousePixelScroll", onWheel, false); > > else < // IE elem.attachEvent ("onmousewheel", onWheel); > function onWheel(e) < e = e || window.event; // wheelDelta не дает возможность узнать количество пикселей var delta = e.deltaY || e.detail || e.wheelDelta; var info = document.getElementById('delta'); info.innerHTML = +info.innerHTML + delta; e.preventDefault ? e.preventDefault() : (e.returnValue = false); > 

    Источник

    Мышь: колёсико, событие wheel

    Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

    Колёсико мыши используется редко. Оно есть даже не у всех мышей. Поэтому существуют пользователи, которые в принципе не могут сгенерировать такое событие.

    …Но, тем не менее, его использование может быть оправдано. Например, можно добавить дополнительные удобства для тех, у кого колёсико есть.

    Отличия колёсика от прокрутки

    Несмотря на то, что колёсико мыши обычно ассоциируется с прокруткой, это совсем разные вещи.

    • При прокрутке срабатывает событие onscroll – рассмотрим его в дальнейшем. Оно произойдёт при любой прокрутке, в том числе через клавиатуру, но только на прокручиваемых элементах. Например, элемент с overflow:hidden в принципе не может сгенерировать onscroll .
    • А событие wheel является чисто «мышиным». Оно генерируется над любым элементом при передвижении колеса мыши. При этом не важно, прокручиваемый он или нет. В частности, overflow:hidden никак не препятствует обработке колеса мыши.

    Кроме того, событие onscroll происходит после прокрутки, а onwheel – до прокрутки, поэтому в нём можно отменить саму прокрутку (действие браузера).

    Зоопарк wheel в разных браузерах

    Событие wheel появилось в стандарте не так давно. Оно поддерживается Chrome 31+, IE9+, Firefox 17+.

    До него браузеры обрабатывали прокрутку при помощи событий mousewheel (все кроме Firefox) и DOMMouseScroll, MozMousePixelScroll (только Firefox).

    Самые важные свойства современного события и его нестандартных аналогов:

    wheel Свойство deltaY – количество прокрученных пикселей по вертикали. Существуют также свойства deltaX и deltaZ для других направлений прокрутки. MozMousePixelScroll Срабатывает, начиная с Firefox 3.5, только в Firefox. Даёт возможность отменить прокрутку и получить размер в пикселях через свойство detail , ось прокрутки в свойстве axis . mousewheel Срабатывает в браузерах, которые ещё не реализовали wheel . В свойстве wheelDelta – условный «размер прокрутки», обычно равен 120 для прокрутки вверх и -120 – вниз. Он не соответствует какому-либо конкретному количеству пикселей.

    Чтобы кросс-браузерно отловить прокрутку и, при необходимости, отменить её, можно использовать все эти события.

    Пример, включающий поддержку IE8-:

    if (elem.addEventListener) < if ('onwheel' in document) < // IE9+, FF17+, Ch31+ elem.addEventListener("wheel", onWheel); >else if ('onmousewheel' in document) < // устаревший вариант события elem.addEventListener("mousewheel", onWheel); >else < // Firefox < 17 elem.addEventListener("MozMousePixelScroll", onWheel); >> else < // IE8- elem.attachEvent("onmousewheel", onWheel); >function onWheel(e) < e = e || window.event; // wheelDelta не даёт возможность узнать количество пикселей var delta = e.deltaY || e.detail || e.wheelDelta; var info = document.getElementById('delta'); info.innerHTML = +info.innerHTML + delta; e.preventDefault ? e.preventDefault() : (e.returnValue = false); >

    Источник

    wheel

    Событие wheel происходит, когда пользователь физически прокручивает колесо мыши, даже если на странице ничего не происходит. За традиционный скролл отвечает событие scroll .

    Как пишется

    Скопировать ссылку «Как пишется» Скопировано

    Отловим все случаи, когда пользователь крутит колесо мыши при наведённом на первый курсоре:

     const div = document.getElementsByTagName('div')[0] div.addEventListener('wheel', function(event)  console.log(event)>) const div = document.getElementsByTagName('div')[0] div.addEventListener('wheel', function(event)  console.log(event) >)      

    Как понять

    Скопировать ссылку «Как понять» Скопировано

    Событие wheel всегда возникает при прокрутке колеса мыши. Попробуйте полистать внутри пустого блока (будет удобнее, если открыть демо в новой вкладке по ссылке внизу):

    Объект события wheel

    Скопировать ссылку «Объект события wheel» Скопировано

    Объект события wheel содержит информацию о направлении и «силе» прокрутки в свойствах:

    • delta X — горизонтальная прокрутка. Значение — целое число:
      • отрицательное, если пользователь прокручивает влево;
      • 0 — если в этом направлении прокрутка не происходит
      • положительное при прокрутке вправо;
      • отрицательное, если пользователь прокручивает вверх;
      • 0 — если в этом направлении прокрутка не происходит
      • положительное при прокрутке вниз;

      С помощью объекта события можно, например, перемещать элемент по экрану при прокрутке колеса мыши на десктопе. Чтобы посмотреть, как это работает, откройте демо в новой вкладке по ссылке внизу.

      Подсказки

      Скопировать ссылку «Подсказки» Скопировано

      💡 Если элемент имеет полосу прокрутки, то обычно после события wheel происходит scroll . Этого можно избежать, вызвав метод события prevent Default ( ) :

       document.addEventListener('wheel', function(event)  // останавливаем поведение по умолчанию, то есть прокрутку event.preventDefault()>) document.addEventListener('wheel', function(event)  // останавливаем поведение по умолчанию, то есть прокрутку event.preventDefault() >)      

      Источник

      Element: mousewheel event

      Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

      Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

      The obsolete and non-standard mousewheel event is fired asynchronously at an Element to provide updates while a mouse wheel or similar device is operated. The mousewheel event was never part of any standard, and while it was implemented by several browsers, it was never implemented by Firefox.

      Note: Instead of this obsolete event, use the standard wheel event.

      Syntax

      Use the event name in methods like addEventListener() , or set an event handler property.

      addEventListener("mousewheel", (event) => >); onmousewheel = (event) => >; 

      Event type

      Event properties

      This interface inherits properties from its ancestors, 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
      WheelEvent.DOM_DELTA_PIXEL 0x00 The delta* values are specified in pixels.
      WheelEvent.DOM_DELTA_LINE 0x01 The delta* values are specified in lines. Each mouse click scrolls a line of content, where the method used to calculate line height is browser dependent.
      WheelEvent.DOM_DELTA_PAGE 0x02 The delta* values are specified in pages. Each mouse click scrolls a page of content.

      WheelEvent.wheelDelta Read only Deprecated Returns an integer (32-bit) representing the distance in pixels. WheelEvent.wheelDeltaX Read only Deprecated Returns an integer representing the horizontal scroll amount. WheelEvent.wheelDeltaY Read only Deprecated Returns an integer representing the vertical scroll amount.

      The detail property

      The value of the detail property is always zero, except in Opera, which uses detail similarly to the Firefox-only DOMMouseScroll event’s detail value, which indicates the scroll distance in terms of lines, with negative values indicating the scrolling movement is either toward the bottom or toward the right, and positive values indicating scrolling to the top or left.

      Note: On macOS, the scroll distance (and therefore the value of detail ) is computed based on the accelerated scroll distance.

      wheelDelta, wheelDeltaX and wheelDeltaY value

      The wheelDelta attribute value is an abstract value which indicates how far the wheel turned. If the wheel has rotated away from the user, it’s positive, otherwise negative. This means that the delta value sign is different from DOM Level 3 Event’s wheel . However, the meaning of the amount of these values is not the same between browsers. See following explanation for the detail. IE and Opera (Presto) only support wheelDelta attribute and do not support horizontal scroll. The wheelDeltaX attribute value indicates the wheelDelta attribute value along the horizontal axis. When a user operates the device for scrolling to right, the value is negative. Otherwise, i.e., if it’s to left, the value is positive. The wheelDeltaY attribute value indicates the wheelDelta attribute value along the vertical axis. The sign of the value is the same as the wheelDelta attribute value.

      Chrome

      On Windows, the value is the same as the delta value of WM_MOUSEWHEEL or WM_MOUSEHWHEEL . And also, the value isn’t changed even if the scroll amount of system settings is page scroll, i.e., the value is the same as IE on Windows. On Linux, the value is 120 or -120 per native wheel event. This makes the same behavior as IE and Chrome for Windows. On Mac, the value is complicated. The value is changed if the device that causes the native wheel event supports continuous scroll. If the device supports continuous scroll (e.g., trackpad of MacBook or mouse wheel which can be turned smoothly), the value is computed from accelerated scroll amount. In this case, the value is the same as Safari. If the device does not support continuous scroll (typically, old mouse wheel which cannot be turned smoothly), the value is computed from non-accelerated scroll amount (120 per notch). In this case, the value is different from Safari. This difference makes a serious issue for web application developers. That is, web developers cannot know if mousewheel event is caused by which device.

      Safari

      The value is always computed from accelerated scroll amount. This is really different from other browsers except Chrome with continuous scroll supported device.

      Opera (Presto)

      The value is always the detail attribute value ✕ 40 . On Windows, since the detail attribute value is computed from actual scroll amount, the value is different from other browsers except the scroll amount per notch is 3 lines in system settings or a page. On Linux, the value is 80 or -80 per native wheel event. This is different from other browsers. On Mac, the detail attribute value is computed from accelerated scroll amount of native event. The value is usually much bigger than Safari’s or Chrome’s value.

      Specifications

      Browser compatibility

      See also

      Источник

      Читайте также:  Python create array range
Оцените статью