js鼠标滚轮事件禁止默认行为preventDefault,兼容各大浏览器

633 阅读1分钟
var scrollFunction = function(e) {
    e = e || window.event;
    e.preventDefault && e.preventDefault(); //禁止浏览器默认事件
    if (e.wheelDelta) { //判断浏览器IE,谷歌滑轮事件
        if (e.wheelDelta > 0) { //当滑轮向上滚动时
            alert("向上&页面不动!")
        }
        if (e.wheelDelta < 0) { //当滑轮向下滚动时
            alert("向下&页面不动!")
        }

    } else if (e.detail) { //Firefox滑轮事件
        if (e.detail > 0) { //当滑轮向上滚动时
            alert("向上&页面不动!")
        }
        if (e.detail < 0) { //当滑轮向下滚动时
            alert("向下&页面不动!")
        }
    }
}
//给页面绑定滑轮滚动事件
if (document.addEventListener) { //firefox
    document.addEventListener('DOMMouseScroll', scrollFunction, false);
}
//滚动滑轮触发scrollFunction方法  //ie 谷歌
window.addEventListener('mousewheel', scrollFunction, {
    passive: false
});