首页 > 代码库 > eventUtil
eventUtil
var eventUtil = {
// 添加句柄
addHandler: function(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else if(element.attachEvent) {
element.attachEvent(‘on‘ + type, handler);
} else {
element[‘on‘ + type] = handler;
}
},
// 删除句柄
removeHandler: function(element, type, handler) {
if(element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if(element.detachEvent) {
element.detachEvent(‘on‘ + type, handler);
} else {
element[‘on‘ + type] = null;
}
},
//获取事件
getEvent: function(event) {
return event ? event : window.event;
},
//获取事件类型
getType: function(event) {
return event.type;
},
//获取元素
getElement: function(event) {
return event.target || event.srcElement;
},
//阻止事件默认行为
preventDefault: function(event) {
if(event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = http://www.mamicode.com/false;
}
},
//阻止事件冒泡
stopPropagation: function(event) {
if(event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
}
window.onload=function(){
var go=document.getElementById(‘go‘),
box=document.getElementById(‘box‘);
eventUtil.addHandler(box,‘click‘,function(){
alert(‘我是整个父盒子‘);
});
eventUtil.addHandler(go,‘click‘,function(e){
//e=eventUtil.getEvent(e);
e=e || window.event;
alert(eventUtil.getElement(e).nodeName);
eventUtil.preventDefault(e);
eventUtil.stopPropagation(e);
});
}
eventUtil