兼容各个浏览器的事件监听代码

时间:2021-06-25 10:51:53
EventUtil = {
/*事件添加*/
addListener:
function(target,type,handler){
if(target.addEventListener){
target.addEventListener(type,handler);
}
else if(target.attachEvent){
target.attachEvent(
'on'+type,function(){
handler.call(target)
/*让handler中的this指向目标元素*/
});
}
else{
target[
'on'+type] = handler;
}
},
/*事件移除*/
removeListener:
function(target,type,handler){
if(target.removeEventListener){
target.removeEventListener(type,handler);
}
else if(target.detachEvent){
target.detachEvent(
'on'+type,handler);
}
else{
target[
'on'+type] = null;
}
},
/*事件对象获取*/
getEvent:
function(e){
var evt = window.event || e;
return evt;
}
/*获取目标对象*/
getTarget:
function(e){
var evt = EventUtil.getEvent(e);
var target;
if(evt.target){
target
= evt.target;
}
else{
target
= evt.srcElement;
}
return target;
}
/*停止冒泡*/
stopPropagation:
function(e){
var evt = EventUtil.getEvent(e);
if(evt.stopPropagation){
evt.stopPropagation();
}
else{
e.cancelBuble
= true;
}
},
/*阻止默认行为*/
preventDefault:
function(e){
var evt = EventUtil.getEvent(e);
if(evt.preventDefault){
evt.preventDefault();
}
else{
evt.returnValue
= false;
}
}
}