项目中正好用到了鼠标滑轮监听事件,于是干脆把它整理成一个方便的JavaScript插件以便于日后有用。
MWheel.js
(function (window, undefined) {
var list = ['up', 'down'],
_this;
var handle = function (event) {
var delta = 0, e;
e = event || window.event;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
if (e.wheelDelta) {
delta = e.wheelDelta / 120;
} else if (e.detail) {
delta = -e.detail / 3;
}
if (delta) {
if (delta < 0) {
if (typeof _this[list[0]] === 'function') {
_this[list[0]].apply(_this, [e]);
}
} else {
if (typeof _this[list[1]] === 'function') {
_this[list[1]].apply(_this, [e]);
}
}
}
};
var MWheel = function (element) {
if (element) {
return new MWheel.fn.init(element);
} else {
return null;
}
};
MWheel.fn = MWheel.prototype = {
constructor: MWheel,
init: function (element) {
var i;
_this = this;
_this.element = element;
for (i = 0; i < list.length; i++) {
_this[list[i]] = null;
}
_this.element.addEventListener('DOMMouseScroll', handle, false);
_this.element.onmousewheel = handle;
}
};
MWheel.fn.init.prototype = MWheel.fn;
MWheel.fn.addEventListener = function (action, fn) {
var i;
for (i = 0; i < list.length; i++) {
if (action === list[i]) {
_this[list[i]] = fn;
}
}
return _this;
};
MWheel.fn.removeEventListener = function () {
_this.element.removeEventListener('DOMMouseScroll', handle);
_this.element.onmousewheel = null;
};
window.MWheel = MWheel;
})(window);
...