各浏览器鼠标滚轮事件

有时候,我们会使用的监听鼠标的滚轮事件,并且判断是向上滚动还是向下滚动;但是,不同的浏览器有不同的滚轮事件。主要是有两种非标准的事件,onmousewheel(firefox不支持)和DOMMouseScroll(只有firefox支持)。代码如下。

//注册事件的兼容写法
if(document.addEventListener){ 
document.addEventListener('DOMMouseScroll',scrollFunc,false); 
}//只有firefox支持,通过判断e.detail的正负来判断上下滚动
window.onmousewheel=document.onmousewheel=scrollFunc;
//IE/Opera/Chrome/safari,通过e.wheelDelta来判断正负

 

根据MDN,以上两种都是非标准的写法,不推荐使用。wheel事件是标准事件,建议使用wheel代替上面的事件。
document/ window .onwheel = function(e) {console.log(e);}
document/window.addEventListener("wheel",(e) => { console.log(e);},false)
//两种写法各个浏览器都支持  

 

posted @ 2020-06-30 23:56  helloworld!!!?  阅读(607)  评论(0)    收藏  举报