JS - 兼容的事件助手

(function () {
// 兼容的事件助手
window.CompatibleEventHelper = {
addEventListener: function (elem, type, cb) {
if (elem.addEventListener) {
elem.addEventListener(type, cb, false);
}
else if (elem.attachEvent) {
elem.attachEvent('on' + type, cb);
}
else {
elem['on' + type] = cb;
}
},
removeEventListener: function (elem, type, cb) {
if (elem.removeEventListener) {
elem.removeEventListener(type, cb, false);
}
else if (elem.detachEvent) {
elem.detachEvent('on' + type, cb);
}
else {
elem['on' + type] = null;
}
},
getEvent: function (event) {
return event || window.event;
},
getTarget: function (event) {
event = this.getEvent(event);
return event.target || event.srcElement;
},
preventDefault: function (event) {
event = this.getEvent(event);
if (event.preventDefault) {
event.preventDefault();
}
else {
event.returnValue = false;
}
},
stopPropagation: function (event) {
event = this.getEvent(event);
if (event.stopPropagation) {
event.stopPropagation();
}
else {
event.cancelBubble = true;
}
}
};
})();

/*
范例:
html:
<div id="box">box</div>

js:
var box = document.getElementById('box');
CompatibleEventHelper.addEventListener(box, 'click', function (event) {
// do something...
});
*/
posted @ 2018-05-08 21:41  AndreMao  阅读(148)  评论(0编辑  收藏  举报