兼容谷歌和火狐的滚轮事件

谷歌向上滚动滚轮是正值,向下是负值,而火狐正好相反

完整测试代码,分别用谷歌和火狐浏览器测试

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            *{
                margin: 0;
                height: 0;
            }
            html,body{
                height: 100%;
            }
            #app{
                width: 100%;
                height: 100%;
                background: #008B8B;
            }
        </style>
    </head>
    <body>
        <div id="app"></div>
        
        <script>
            window.onload = function(){
                var appNode = document.querySelector("#app");
                for(var i=0; i<200;i++){
                    appNode.innerHTML += "Bear"+(i)+"<br>";
                }
                function fn(ev){
                    ev = ev || event;
                    //滚轮方向
                    var dir = "";
                    console.log("我是谷歌:"+ ev.wheelDelta);
                    console.log("我是火狐:"+ ev.detail);
                    if(ev.wheelDelta){
                        console.log(ev.wheelDelta);
                        if(ev.wheelDelta>0){
                            dir = "up";
                        }else if(ev.wheelDelta<0){
                            dir = "down";
                        }
                    }else if(ev.detail){
                        if(ev.detail>0){
                            dir = "down";
                        }else if(ev.detail<0){
                            dir = "up";
                        }
                    }
                    console.log(dir);
                    switch(dir){
                        case "up":
                            appNode.style.height = appNode.offsetHeight - 10 + "px";
                            break;
                        case "down":
                            appNode.style.height = appNode.offsetHeight + 10 + "px";
                            break;
                    }
                    
                    ev.preventDefault();
                }

                // 谷歌
                appNode.addEventListener("mousewheel",fn);
                // 火狐
                appNode.addEventListener("DOMMouseScroll",fn);

            }
        </script>
    </body>
</html>

 

posted @ 2019-04-14 11:30  卖鱼熊  阅读(615)  评论(0编辑  收藏  举报