This article mainly introduces the relevant information about disabling mouse wheel events in JavaScript. Friends in need can refer to it.
We usually adjust the compatibility of lower versions of IE when it comes to compatible things, but this time it’s not because the lower version of the browser is incompetent. It's because Firefox has gone too far and completely disregards the experience of other browsers. All browsers except Firefox can use the MouseWheel event to handle the response of the mouse wheel. However, Firefox does not support MouseWheel, and uses the nonsensical DOMMouseScroll, which is not compatible with other browsers except Firefox. In other words, for handling mouse wheel events, Firefox can only use DOMMouseScroll. Non-Firefox can only use MouseWheel. The principles of these two events are different, and the data they process is also different.
- varfirefox=navigator.userAgent.indexOf('Firefox')!=-1;
- firefox?img.addEventListener('DOMMouseScroll',MouseWheel,false):
- (img.onmousewheel=MouseWheel);
- functionMouseWheel(e){
- e=e||window.event;
- if(e.stopPropagation)e.stopPropagation();
- elsee.cancelBubble=true;
- if(e.preventDefault)e.preventDefault();
- elsee.returnValue=false;
- }
Let’s take a look at the complete code
- <!DOCTYPEhtml>
- <style>
- span{font:14px/20pxMicrosoft Yahei;}
- #counter{
- width:50px;height:20px;
- border:1pxsolid#CCC;
- background:#F9F9F9;
- font:14px/20pxConsolas;
- text-align:center;
- margin:10px;
- }
- </style>
- <span>Use the mouse wheel to adjust the value</span><br/>
- <divid=counter>0</div>
- <script>
- //Judge the browser
- varisIE=navigator.userAgent.match(/MSIE(/d)/i);
- isIE=isIE?isIE[1]:undefined;
- varisFF=/FireFox/i.test(navigator.userAgent);
- //Get elements
- varcounter=document.getElementById(counter);
- //Mouse wheel event
- if(isIE<9)//Traditional browsers use MouseWheel event
- counter.attachEvent(onmousewheel,function(){
- //Calculate the distance the mouse wheel scrolls
- //One grid has 3 lines, each line has 40 pixels, so divide by 120
- varv=event.wheelDelta/120;
- counter.innerHTML=counter.innerHTML*1+v;
- //Block browser default method
- returnfalse;
- });
- elseif(!isFF)//Modern browsers except Firefox also use the MouseWheel event
- counter.addEventListener(mousewheel,function(e){
- //Calculate the distance the mouse wheel scrolls
- varv=e.wheelDelta/120;
- counter.innerHTML=counter.innerHTML*1+v;
- //Block browser default method
- e.preventDefault();
- },false);
- else//The weird Firefox uses the DOMMouseScroll event
- counter.addEventListener(DOMMouseScroll,function(e){
- //Calculate the distance the mouse wheel scrolls
- //One grid is 3 lines, but please note that the difference here from pixels is that it is a negative value
- varv=-e.detail/3;
- counter.innerHTML=counter.innerHTML*1+v;
- //Block browser default method
- e.preventDefault();
- },false);
- </script>
The above is the entire content of this article, I hope you all like it.