兼容谷歌和火狐的滾輪事件

谷歌向上滾動滾輪是正值,向下是負值,而火狐正好相反html

完整測試代碼,分別用谷歌和火狐瀏覽器測試瀏覽器

 

<!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>
相關文章
相關標籤/搜索