首页 > 网站 > WEB开发 > 正文

写一个通用的事件监听函数

2024-04-27 15:05:32
字体:
来源:转载
供稿:网友
  var Event = {   //页面加载完成后   readyEvent:function(fn){    if(fn == null){     fn = document;    }    var oldonload = window.onload;    if(typeof window.onload != 'function'){     window.onload = fn;    }else{     window.onload = function(){      oldonload();      fn();     }    }   },   //添加事件   addEvent:function(element,type,hander){    if(element.addEventListener){ //非IE     //事件类型,需要执行的函数,是否捕获     element.addEventListener(type,hander,false);    }else if(element.attachEvent){ //IE     element.attachEvent("on"+type,function(){      hander.call(element);     })    }else{     element["on"+type] = hander;    }   },   //移除事件   removeEvent:function(element,type,hander){    if(element.removeEventListener){     element.removeEventListener(type,hander,false)    }else if(element.attachEvent){     element.attachEvent("on"+type,hander);    }else{     element["on"+type] = null;    }   },   //阻止事件   stopPRopagation:function(event){    if(event.stopPropagation){     event.stopPropagation();//w3c标准    }else{     event.cancelBubble = true; //ie         }   },   //取消默认事件   preventDefault:function(event){    if(event.preventDefault){     event.preventDefault();    }else{     event.returnValue = false; //ie    }   },   //获取事件目标   getTarget:function(event){    return event.target || event.srcElement;   },   //获取event对象的引用,取到事件的所有信息,确保随时能使用event;   getEvent:function(e){    var even = e || window.event;    if(!even){     var c = this.getEvent.caller;     while(!c){      even = c.arguments[0];      if(even && Event == even.constructor){     break;        }      c = c.caller;     }    }    return even;   }     }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表