Skip to content

Instantly share code, notes, and snippets.

@tonyc726
Last active October 19, 2016 03:29
Show Gist options
  • Save tonyc726/87d02cd6c14a22c2d0bc to your computer and use it in GitHub Desktop.
Save tonyc726/87d02cd6c14a22c2d0bc to your computer and use it in GitHub Desktop.
JavaScript高级程序设计之EventUtil
// 简单的通用事件方法
// http://www.imooc.com/wenda/detail/4603
var EventUtil = {
getEvent: function (e) {
return e || window.event;
},
getTarget: function (e) {
return e.target || e.srcElement;
},
preventDefault: function (e) {
if (e && e.preventDefault) {
e.preventDefault();
} else {
window.event.returnValue = false;
}
},
stopPropagation: function (e) {
if (e && e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
},
addHandler: function (ele, evType, fn, useCapture) {
// 默认使用事件冒泡
useCapture = useCapture || false;
if (ele.addEventListener) {
ele.addEventListener(evType, fn, useCapture);
} else if (ele.attachEvent) {
ele.attachEvent("on" + evType, function () {
// fn中的this指向ele对象:ie的问题
fn.call(ele);
});
} else {
ele["on" + evType] = fn;
}
},
dispatchHandler: function (ele, evType, enableCapture, enableDefault) {
// 默认禁用事件冒泡
enableCapture = enableCapture || false;
// 默认禁用浏览器的默认行为
enableDefault = enableDefault || false;
if (document.createEventObject){
// IE浏览器支持fireEvent方法
var evt = document.createEventObject();
return ele.fireEvent('on'+evType, evt);
}
else{
// 其他标准浏览器使用dispatchEvent方法
var evt = document.createEvent( 'HTMLEvents' );
// initEvent接受3个参数:
// 事件类型,是否冒泡,是否阻止浏览器的默认行为
evt.initEvent(evType, enableCapture, enableDefault);
return !ele.dispatchEvent(evt);
}
},
removeHandler: function (ele, evType, fn) {
if (ele.removeEventListener) {
ele.removeEventListener(evType, fn);
} else if (ele.detachEvent) {
ele.detachEvent("on" + evType, fn);
} else {
ele["on" + evType] = null;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment