--- 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")}} 对象作为唯一的传入参数。
以下例子展示了如何使用鼠标(或其它光标设备)的滚轮来缩放一个元素。
<div>Scale me with your mouse wheel.</div>
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; }
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')}} |
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") }} 事件。