0%

JS滚轮事件(mousewheel/DOMMouseScroll)

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
兼容滚轮事件的方法
兼容 safari,chrome和firefox的函数
var addEvent = (function(window, undefined) {
var _event = function(event) {
var type = event.type;
if (type === 'DOMMouseScroll' || type === 'mousewheel') {
console.log(event)
event.delta = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0);
}
if (event.srcElement && !event.target) {
event.target = event.srcElement;
}
if (!event.preventDefault && event.returnValue !== undefined) {
event.preventDefault = function() {
event.returnValue = false;
}
}
return event;
};
if (window.addEventListener) {
return function(el, type, fn, capture) {
if (type === 'mousewheel' && document.mozFullScreen !== undefined) {
type = "DOMMouseScroll";
}
el.addEventListener(type, function(event) {
fn.call(this, _event(event));
}, capture || false);
}
} else if (window.attachEvent) {
return function(el, type, fn, capture) {
el.attachEvent("on" + type, function(event) {
event = event || window.event;
fn.call(el, _event(event));
});
}
}
})(window);

测试使用方法如下:

1
2
3
4
5
6
addEvent(window, "mousewheel", function(event) {
console.log(event.delta);
if(event.delta < 0) {
console.log('鼠标向下滚动了');
}
});