欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-05 15:17:56
谷歌向上滚动滚轮是正值,向下是负值,而火狐正好相反 完整测试代码,分别用谷歌和火狐浏览器测试 ......

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

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

 

<!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>