Javascript monitoring of mouse wheel events

  • 2020-03-30 03:10:38
  • OfStack

We've all seen these effects, either by using a mouse wheel to add or subtract Numbers from a form, or by using a wheel to move a button around and up and down. All of these are realized by js monitoring the events of the mouse wheel. Today here is a simple js for mouse wheel event monitoring.

Different events for different browsers

Js returns a numeric value to determine whether the wheel is up or down

Determining whether the wheel is going up or down in the browser is also a matter of compatibility. Firefox now USES detail in the five major browsers (IE, Opera, Safari, Firefox, Chrome) and wheelDelta in the remaining four. The detail and wheelDelta only take two values each, the detail only takes plus or minus 3, and the wheelDelta only takes plus or minus 120, where positive Numbers mean up and negative Numbers mean down.
The specific code is as follows:


<label for="wheelDelta"> The scroll values :</label>(IE/Opera)<input type="text" id="wheelDelta"/>
<label for="detail"> The scroll values :(Firefox)</label><input type="text" id="detail"/>
<script type="text/javascript">
var scrollFunc=function(e){
    e=e || window.event;
    var t1=document.getElementById("wheelDelta");
    var t2=document.getElementById("detail");
    if(e.wheelDelta){//IE/Opera/Chrome
        t1.value=e.wheelDelta;
    }else if(e.detail){//Firefox
        t2.value=e.detail;
    }
}

if(document.addEventListener){
    document.addEventListener('DOMMouseScroll',scrollFunc,false);
}//W3C
window.onmousewheel=document.onmousewheel=scrollFunc;//IE/Opera/Chrome
</script>


By running the above code, we can see:


In the firefox In the browser, the value of the scroll wheel scrolling up is 120 , scroll down to return -120
And in the firefox In the browser, the value of the scroll wheel scrolling up is -3 , scroll down to return 3
The code section is as follows, e.wheelDelta It is to judge whether it is right or not firefox The browser, e.detail for firefox The browser
if(e.wheelDelta){//IE/Opera/Chrome
t1.value=e.wheelDelta;
}else if(e.detail){//Firefox
t2.value=e.detail;
}

  PS: here again for you to recommend an online query tool about JS events, summed up the common JS event types and functions:

Javascript events and function description:

(link: http://tools.jb51.net/table/javascript_event)


Related articles: