<!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>Document</title>
<style>
div{
width:150px;
height:150px;
background-color:red;
}
</style>
</head>
<body>
<div></div>
<script>
// 下面这种写法,mousewheel在谷歌和ie浏览器有效果
// document.mousewheel=function(){
// console.log(1);
// }
// 这种写法;只支持火狐浏览器(在火狐中鼠标滚动会连续出现1)
// document.addEventListener("DOMMouseScroll",function(){
// console.log(1);
// },false);
// 实现的效果:鼠标在谁身上滚动,向下滚动向上滚动所执行的函数
var oDiv=document.querySelector("div");
mWheel(oDiv,{
"up":function(){
this.style.backgroundColor="blue"; //这里的this可以写成oDiv
},
"down" :function(){
this.style.backgroundColor="yellow";
}
})
// 鼠标滚轮事件的封装
function mWheel(obj,twoFn){
// 判断是否将up和down两个对象传过来了(如果没传,下面的twoFn.up()和twoFn.down()为undefied)
twoFn.up=twoFn.up || function(){} ; //后面是匿名函数,作用:空转什么也不干
twoFn.down=twoFn.down || function(){} ;
// 判断是火狐浏览器还是ie还是谷歌
if(window.navigator.userAgent.indexOf("Firefox")== -1){ //不是火狐浏览器
obj.onmousewheel =function(){
// uod(event); //event是实参,传给函数uod,因为uod要用到ev,而ev是事件对象(只有事件函数才有event)
// uod(event) ? twoFn.up() : twoFn.down(); //看uod(event)的返回值,返回值是true则执行向上的函数,否则执行向下的函数。但twoFn.up()是直接调用函数,直接调用函数this指向window,所以要改变up和down中this的指向
uod(event) ? twoFn.up.call(this) : twoFn.down.call(this);
return false; //如果我们想在滚轮滚动时不要移动滚动条就需要阻止浏览器默认行为。
}
}else{
obj.addEventListener("DOMMouseScroll",function(){
console.log(event.detail);
uod(event) ? twoFn.up.call(this) : twoFn.down.call(this); // uod(event)的返回值如果是true则为冒号的前面语句
event.preventDefault(); //火狐浏览器取消默认行为
},false);
}
}
// 判断滚轮是向上滚动,还会向下滚动
function uod(ev){//up or down(uod)
if(window.navigator.userAgent.indexOf("Firefox")== -1){
// return ev.wheelDelta == 120 ? true :false;
return ev.wheelDelta > 0 ? true :false;
}else{
return ev.detail < 0 ? true : false;
}
}
// console.log(window.navigator.userAgent); //会输出一串字符串,里面包含了Firefox
</script>
</body>
</html>
鼠标滚轮事件的封装过程
最新推荐文章于 2022-04-18 08:56:56 发布