addEvent.repeat = function(type,fn){ for(var i in type){ if(type[i] == fn){ return true; } return false; } }; addEvent.fn = function(){ var e = addEvent.fixEvent(window.event); for(var i in this.events[e.type]){ this.events[e.type][i].call(this,e); } }; //fixEvent : 处理IE的事件对象 addEvent.fixEvent = function(e){ e.preventDefault = function(){ e.returnValue = false; }; e.stopPropagation = function(){ e.cancelBubble = true; }; e.target = e.srcElement; if('mouseover' == e.type){ e.relatedTarget = e.fromElement; } if('mouseout' == e.type){ e.relatedTarget = e.toElement; } return e; }; //添加事件 function addEvent(obj,type,fn){ if(typeof obj.addEventListener != 'undefined'){ obj.addEventListener(type,fn,false); }else{ if(!obj.events) obj.events = {}; if(!obj.events[type]){ obj.events[type] = []; } if(!addEvent.repeat(obj.events[type],fn)){ obj.events[type].push(fn); } obj['on' + type] = addEvent.fn; } } //移除事件 function removeEvent(obj,type,fn){ if(typeof obj.removeEventListener != 'undefined'){ obj.removeEventListener(type,fn,false); }else{ if(obj.events){ for(var i in obj.events[type]){ if(obj.events[type][i] == fn){ delete obj.events[type][i]; } } } } }
用法:
var test = document.getElementById("test"); //给test元素添加点击事件,执行fn1 addEvent(test,'click',fn1); //给test元素移除点击事件 removeEvent(test,'click',fn1); function fn1(){ alert("fn1"); }