js监听鼠标滚动事件,兼容各大浏览器

开始之前,我们先来看看关于不同浏览器滚动事件的属性差异:

Chrome IE Safari Opera浏览器的属性:wheelDelta
wheelDelta取值为±120,+120表示滚轮向上,-120表示滚轮向下
Firefox浏览器滚动事件的属性:detail
wheelDelta取值为±3,+3表示滚轮向上,-3表示滚轮向下

不同的浏览器有不同的滚轮事件。主要是有两种:

一、onmousewheel(IE/Opera/Chrome支持,firefox不支持)

二、DOMMouseScroll(只有firefox支持)  

兼容写法:

if (document.addEventListener) { 
document.addEventListener('DOMMouseScroll', scrollFunc, false); //scrollFunc为定义的事件名
}

window.onmousewheel = document.onmousewheel = scrollFunc; //scrollFunc为定义的事件名

示例代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>js监听鼠标滚动事件,兼容各大浏览器</title>
<script type="text/javascript">
var scrollFunc = function(e) {
e = e || window.event;
if (e.wheelDelta) { //第一步:先判断浏览器IE,谷歌事件
if (e.wheelDelta > 0) { //当向上滚动时
console.log("向上滚动");
}
if (e.wheelDelta < 0) { //当向下滚动时
console.log("向下滚动");
}
} else if (e.detail) { //Firefox事件
if (e.detail > 0) { //当向上滚动时
console.log("向上滚动");
}
if (e.detail < 0) { //当向下滚动时
console.log("向下滚动");
}
}
}
//给页面绑定滚动事件
if (document.addEventListener) { //firefox
document.addEventListener('DOMMouseScroll', scrollFunc, false);
}
//滚动触发scrollFunc方法 //ie 谷歌
window.onmousewheel = document.onmousewheel = scrollFunc;
</script>
</head>
<body>
<div style="height: 2000px;background-color: #f00;"></div>
</body>
</html>

注:浏览器F12滚动鼠标即可查看滚动效果提示!


六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!