JS鼠标滚轮事件解析

时间:2022-08-05 08:02:10

一、不同浏览器的鼠标滚轮事件

首先,不同的浏览器有不同的滚轮事件。主要是有两种,onmousewheel(IE/Opera/Chrome支持,firefox不支持)和DOMMouseScroll(只有firefox支持)

另外在操作的过程中需要添加事件监听,兼容性写法

代码如下:

/*注册事件*/
if(document.addEventListener){
document.addEventListener('DOMMouseScroll',scrollFunc,false); // W3C
}
window.onmousewheel=document.onmousewheel=scrollFunc; // IE/Opera/Chrome

二、通过js事件event对象的返回数值判断滚轮上下

判断滚轮向上或向下在浏览器中也要考虑兼容性,现在五大浏览器(IE、Opera、Safari、Firefox、Chrome)中Firefox 使用detail,其余四类使用wheelDelta;

两者只在取值上不一致,代表含义一致,detail与wheelDelta只各取两个值,detail只取±3,wheelDelta只取±120,其中正数表示为向上,负数表示向下。

代码如下:

<label for="wheelDelta">滚动值:</label>(IE/Opera)<input type="text" id="wheelDelta"/>
<label for="detail">滚动值:(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>

效果如下:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjcAAAAmCAYAAAA4Pbq5AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAk+SURBVHhe7ZzNceM4EIWVkS5ORydnMRno4Fx0cSY6TTJcoNEg+g+gpIFFF/d9VdgZUiDQAPs9NmXPnhYAAAAAgAOB4gYAAAAAhwLFDQAAAAAOBYobAAAAABwKFDcAAAAAOBQobgAA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EQQAAFgoGkEAAICFohEEAABYKBpBAACAhaIRBAAAWCgaQQAAgIWiEQQAAFgoGkEAAIBFSuknpfPeH1Js5ccAAAAASUVORK5CYII=" alt="" />

通过运行上述代码我们可以看到:

在非firefox浏览器中,滚轮向上滚动返回的数值是120,向下滚动返回-120。
而在firefox浏览器中,滚轮向上滚动返回的数值是-3,向下滚动返回3

代码部分如下,e.wheelDelta是判断是否为非firefox浏览器,e.detail为firefox浏览器

if(e.wheelDelta){   // IE/Opera/Chrome
t1.value=e.wheelDelta;
}else if(e.detail){ // Firefox
t2.value=e.detail;
}