如何区分鼠标滚轮Roll up与Roll down事件并绑定对应函数
Great question! The core issue here is that both onmousewheel (an older non-standard event) and onscroll fire anytime scrolling occurs—they don’t inherently carry information about which direction the wheel was rolled. To fix this, we need to capture the scroll direction directly from the event object itself.
Modern Cross-Browser Solution
Use the standard wheel event (supported by all modern browsers), which provides clear direction data via the deltaY property:
- A positive
deltaYvalue means the user rolled the wheel down - A negative
deltaYvalue means the user rolled the wheel up
Here’s how to implement this with your existing functions:
function up() { alert("you rolled up with mouse wheel"); } function down() { alert("you rolled down with mouse wheel"); } // Bind to the document (or a specific element if you only want it there) document.addEventListener('wheel', function(event) { // Optional: Prevent default page scrolling if you don't want it to happen // event.preventDefault(); if (event.deltaY > 0) { // Wheel rolled down down(); } else { // Wheel rolled up up(); } });
Key Notes to Avoid Duplicate Triggers
- Don’t bind both
wheelandmousewheelevents at the same time—this will cause your functions to run twice per wheel movement. - If you need support for very old browsers (like IE9 and below), you can fall back to
mousewheeland check thewheelDeltaproperty (positive = up, negative = down):document.addEventListener('mousewheel', function(event) { event.wheelDelta > 0 ? up() : down(); }); - Only use
event.preventDefault()if you intentionally want to block default scrolling behavior—overusing this can break user expectations.
Why Your Original Approach Didn’t Work
onscroll fires after scrolling completes (regardless of whether it came from the wheel, touch, or keyboard), so it can’t tell you how the scroll was initiated. onmousewheel does fire on wheel movement, but without checking its built-in properties, you have no way to distinguish up vs down—leading to both functions triggering if you tried to bind them directly.
内容的提问来源于stack exchange,提问作者Iman Emadi




