event事件对象的兼容

时间:2021-02-03 00:19:01
var event = {

// 添加事件监听
add: function(element, type, callback){

if(element.addEventListener){
element.addEventListener(type, callback,
false);
}
else if(element.attachEvent){
element.attachEvent(
'on' + type, callback);
}
else {
element[
'on' + type] = callback;
}
},

// 移除事件监听
remove: function(element, type, callback){

if(element.removeEventListener){
element.removeEventListener(type, callback,
false);
}
else if(element.detachEvent){
element.detachEvent(
'on' + type, callback);
}
else {
element[
'on' + type] = null;
}

},

// event 对象
getEvent: function(event){

return event ? event : window.event;
},

// 获取目标元素
getTarget: function(event){

return event.target || event.srcElement;
},

// 阻止事件的默认行为
preventDefault: function(event){

if(event.preventDefault){
event.preventDefault();
}
else {
event.returnValue
= false;
}
},

// 阻止冒泡
stopPropagation: function(){

if(event.stopPropagation){
event.stopPropagation();
}
else {
event.cancelBubble
= true;
}
}

};