GlobalEventHandlers.onwheel

归纳说明

GlobalEventHandlers 的 onwheel 特性指向当前元素的滑轮滑动事件函数 EventHandler

注意:不要混淆 onwheel 和 onscrollonwheel 通常用于处理滑轮的滚动事件,而 onscroll 用于处理某个对象内容的滚动。

语法

target.onwheel = functionRef;

functionRef 是一个函数名或者函数表达式。该函数接受一个 WheelEvent 对象作为唯一的传入参数。

举例

以下例子展示了如何使用鼠标(或其它光标设备)的滚轮来缩放一个元素。

HTML

<div>Scale me with your mouse wheel.</div>

CSS

body {
  min-height: 100vh;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

div {
  width: 80px;
  height: 80px;
  background: #cdf;
  padding: 5px;
  transition: transform .3s;
}

JavaScript

function zoom(event) {
  event.preventDefault();

  if (event.deltaY < 0) {
    // 放大
    scale *= event.deltaY * -2;
  }
  else {
    // 缩小
    scale /= event.deltaY * 2;
  }

  // 限制缩放
  scale = Math.min(Math.max(.125, scale), 4);

  // 应用缩放过渡效果
  el.style.transform = `scale(${scale})`;
}

let scale = 1;
const el = document.querySelector('div');
document.onwheel = zoom;

结果

详情指南

Specification Status Comment
HTML Living Standard
onwheel
Living Standard

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Android Webview Chrome for Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

注意

当用户在相应元素上滚动滑轮便触发 wheel 事件。

参见