js判断浏览器滚动方向需要做兼容,jq这块并没去封装特定方法,所以每次还是需要依赖原生去弄下,特此写个demo,方便大家复制粘贴使用。因为不同的浏览器有不同的滚轮事件。主要是有两种,onmousewheel(firefox不支持)和DOMMouseScroll(只有firefox支持),在这个问题上,我只能说火狐真操蛋,IE都兼容性那么好,而它就是要与众不同。。。
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| <!DOCTYPE html >
<html lang ="en">
<head >
<meta charset ="UTF-8">
<meta name ="viewport" content ="width=device-width, initial-scale=1.0">
<meta http -equiv ="X-UA-Compatible" content ="ie=edge">
<title >判断浏览器滚轮方向 </title >
<style >
body {
height : 2000px ;
}
.mian {
position : fixed ;
top : 10px ;
left : 0;
}
</style >
</head >
<body >
<div class="mian">
<p id ='wheelDelta'>当前滚动值: </p >
</div >
<script type ="text/javascript">
//IE/Opera/Chrome通过e.wheelDelta上120,下为-120;Firefox通过e.xdetail 上为-3,下为3
var t1 = document .getElementById ("wheelDelta");
var scrollFunc = function (e ) {
e = e || window .event ;
console .log(e .wheelDelta )
if (e .wheelDelta == 120) {
console .log('非火狐浏览器,上')
} else if (e .wheelDelta == -120) {
console .log('非火狐浏览器,下')
} else if (e .detail == 3) {
console .log('火狐浏览器,下')
} else {
console .log('火狐浏览器,上')
}
t1 .innerHTML = '当前滚动值:' + (e .wheelDelta || e .detail )
}
// 节流
function conduct (fn , delay , masExac ) {
var timer ;
var lastTime = new Date();
return function (arg ) {
var now = new Date();
clearTimeout (timer )
if (now - lastTime < masExac ) {
timer = setTimeout (function(){
fn (arg );
lastTime = now ;
}, delay )
} else {
fn (arg );
lastTime = now ;
}
}
}
/*DOMMouseScroll只有火狐支持*/
if (document .addEventListener ) {
document .addEventListener ('DOMMouseScroll', conduct (scrollFunc ,1000,2000), false);
}
//IE/Opera/Chrome
document .onmousewheel = conduct (scrollFunc ,1000,2000);
</script>
</body >
</html > |
小结
主要做的兼容就是Firefox另类,它需要通过DOMMouseScroll事件才能拿到滚动信息,在非火狐浏览器(firefox)中,e.wheelDelta 滚轮向上滚动返回的数值是120,向下滚动返回-120,而在firefox浏览器中,e.detail滚轮向上滚动返回的数值是-3,向下滚动返回3。
在线一览
「梦想一旦被付诸行动,就会变得神圣,如果觉得我的文章对您有用,请帮助本站成长」
共 0 条评论关于"js原生判断浏览器滚轮滚动方向+滚动事件节流+兼容IE5+"
最新评论