js鼠标滚轮事件

来源:互联网 发布:mysql字段值累加 编辑:程序博客网 时间:2024/05/16 04:38

js鼠标滚轮事件

有时候我们想做的效果涉及到鼠标滚轮事件,比如全屏滑动或者鼠标滚动切换页面部分,再比如滚轮控制大小缩放,鼠标滚轮事件有浏览器兼容性问题,网上也有讲解,不过多数ctrl+c ctrl+v,有漏洞,不能轻易相信(包括这篇),强烈建议自己动手实践下

我的测试环境:谷歌,IEEdge,欧朋,火狐

丑话说到前头:历来我们都被IE的兼容问题搞的欲仙欲死,不过这次世道变了,鼠标滚轮事件的兼容性批斗的是火狐;

1.事件绑定

探讨属性document.onmousewheel:
类似object.onclick,是一个鼠标滚轮事件句柄;在谷歌,IE,欧朋中,document.onmousewheel类型为object,也就是存在这个句柄,现在我们把这些浏览器称为第一类浏览器;而在火狐中其类型为“undefined”,把火狐称为第二类浏览器

  1. 第一类:谷歌,IE,欧朋
  2. 第二类:火狐

所以对于第一类浏览器可直接定义事件:

document.onmousewheel=function(){//  谷歌,IE,欧朋            myFunction();        };

而对于第二类浏览器:

document.addEventListener("DOMMouseScroll",myFunction,false)//火狐

所以,兼容方法:

if(typeof(document.onmousewheel) == "undefined"){     document.addEventListener("DOMMouseScroll",myFunction,false)//火狐 }else{     document.onmousewheel=function(){//  谷歌,IE,欧朋         myFunction();     }; }
2.事件数据处理

首先,事件处理函数要把事件传过来

 function mouseToggle(e){     e= e || window.event;//火狐,IE,e不用赋值,谷歌,欧朋 e=window.event           }

而对于谷歌和欧朋也可以不用给e赋值,前提要在绑定事件时把e传过来:

document.onmousewheel=function(e){         myFunction(e);     };//个人感觉用上面的方法比较简洁

对于第一类浏览器,滚轮数据存储在e.wheelDelta:
- 向下滚动:e.wheelDelta返回-120
- 向上滚动:e.wheelDelta返回120

对于第二类浏览器滚轮数据存储在e.detail:
- 向下滚动:e.detail返回3
- 向上滚动:e.detail返回-3

第一类浏览器向下滚动返回负数,向上返回正数,第二类浏览器相反

事故:IE浏览器中每滚一次鼠标,事件会触发两次

完整代码:

    if(typeof (document.onmousewheel) == "undefined"){        document.addEventListener("DOMMouseScroll",myFunction,false)    }else{        document.onmousewheel=function(){            myFunction();        };    }    function myFunction(e){        var direction;        e = e || window.event;        if(e.wheelDelta){            direction=e.wheelDelta;        }else if(e.detail){            direction=e.detail;        }        if(direction == -120 || direction == 3){            direction = "向下";        }else if(direction == 120 || direction == -3){            direction = "向上";        }               alert(direction)    }

如有BUG还望指正:

留言评论或
QQ:3267047344

0 0