--- title: GlobalEventHandlers.onwheel slug: Web/API/GlobalEventHandlers/onwheel tags: - API - DOM - Event Handler - GlobalEventHandlers - Property - Reference - onwheel translation_of: Web/API/GlobalEventHandlers/onwheel ---

{{ ApiRef("DOM") }}

归纳说明

{{domxref("GlobalEventHandlers")}} 的 onwheel 特性指向当前元素的滑轮滑动事件函数 {{event("Event_handlers", "event handler")}}。

注意:不要混淆 onwheel 和 {{domxref("GlobalEventHandlers.onscroll", "onscroll")}}:onwheel 通常用于处理滑轮的滚动事件,而 onscroll 用于处理某个对象内容的滚动。

语法

target.onwheel = functionRef;

functionRef 是一个函数名或者函数表达式。该函数接受一个 {{domxref("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;

结果

{{EmbedLiveSample("Examples", 700, 400)}}

详情指南

Specification Status Comment
{{SpecName('HTML WHATWG','webappapis.html#handler-onwheel','onwheel')}} {{Spec2('HTML WHATWG')}}

浏览器兼容性

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Feature Android Android Webview Chrome for Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

注意

当用户在相应元素上滚动滑轮便触发 {{ event("wheel") }} 事件。

参见