鼠标滚轮事件---兼容

Posted zhanghua-zh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了鼠标滚轮事件---兼容相关的知识,希望对你有一定的参考价值。

鼠标滚轮事件绑定及滚轮方向兼容demo

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }
            #test{
                width: 200px;
                height: 200px;
                background: pink;
                position: absolute;
                left: 0;
                right: 0;
                top: 0;
                bottom: 0;
                margin: auto;
            }
            
        </style>
    </head>
    <body>
        <div id="test"></div>
    </body>
    <script type="text/javascript">
        
        window.onload=function(){
            var testNode = document.querySelector("#test");

            // 事件绑定:火狐
            if(testNode.addEventListener){
                testNode.addEventListener("DOMMouseScroll",fn);
            }

            // 事件绑定:非火狐浏览器
            testNode.onmousewheel=fn;
            
            // 滚轮方向
            function fn(ev){
                ev=ev||event;
                var dir="";
                if(ev.wheelDelta){
                    dir = ev.wheelDelta>0?"up":"down";// 非火狐浏览器
                }
                if(ev.detail){
                    dir = ev.detail<0?"up":"down"; // 火狐
                }
                
                console.log(dir)
            }
            
        }
        
        
    </script>
</html>

以上是关于鼠标滚轮事件---兼容的主要内容,如果未能解决你的问题,请参考以下文章

鼠标滚轮事件---兼容火狐

各浏览器鼠标滚轮事件

监听鼠标滚轮事件

事件捕获冒泡绑定赋值委托兼容滚轮

JavaScript鼠标滚轮事件

滚轮事件整理