一、mousewheel鼠标滚轮事件

一、mousewheel鼠标滚轮事件

1.1 定义一个函数,实现多个浏览器的绑定

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
// 定义一个函数,可以实现多个浏览器的事件绑定
function bindEvent(dom, type, fn){

// 判断type类型
if (type.toLowerCase() === "mousewheel"){
// 判断是否是火狐浏览器
var isFF = window.navigator.userAgent.indexOf("Firefox") === - 1 ? false : true;
// console.log(isFF);
// 如果是火狐 要添加DOMMouseScroll事件
if (isFF){
dom.addEventListener("DOMMouseScroll", fn, false);
return;
}
}
// 使用能力检测,检测浏览器支持哪种浏览器
if (dom.addEventListener){
// 说明是高级浏览器 IE没有第三个参数,只支持冒泡,在这里直接写死,绑定到冒泡阶段
dom.addEventListener(type, fn, false);
} else if (dom.attachEvent){
// 说明是IE中的高级版本
dom.attachEvent("on" + type, fn);
} else {
// 说明是其他不知名浏览器
// dom.onclick = function(){}
dom["on" + type] = fn;
}
}

1.2 onmousewheel事件

该事件触发的条件:当鼠标滚轮上下滚动的时候

兼容性:

火狐不支持mousewheel事件,支持DOMMouseScroll事件

绑定方式:

1
2
3
4
// 给document绑定鼠标滚动事件
document.onmousewheel = function(){
console.log("滚动滚轮了");
}
  • 在chrome中:

UM25nA.png

  • 在IE中:

UM2Htf.png

  • 在火狐浏览器中:

    • 滚动滚轮,没有反应

    • 原因是火狐不支持mousewheel事件

支持方式:

1
2
3
4
5
document.addEventListener(“DOMMouseScroll”, function(){});

document.addEventListener("DOMMouseScroll", function(){
console.log("火狐中滚动");
});

UM2xns.png

1.3 阻止默认事件

1
2
3
4
5
6
7
8
9
10
11
12
bindEvent(document, "mousewheel", function(e){
console.log(123);
// 阻止默认onscroll事件,使得滚动鼠标时,滚动条不发生改变
// e.preventDefault();
if (e.preventDefault){
// 谷歌 火狐中阻止默认事件执行的方式
e.preventDefault();
} else {
// IE中阻止默认事件执行的方式
e.returnValue = false;
}
});
点击查看

本文标题:一、mousewheel鼠标滚轮事件

文章作者:Mango

发布时间:2020年07月13日 - 23:12:38

最后更新:2020年07月14日 - 13:27:10

原始链接:https://mango185.github.io/post/2341c19b.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------