首页 > 代码库 > 事件对象库

事件对象库

 1 //事件对象库; 2 var EventUtil={ 3     addEvent:function(obj,type,fn){ 4         if(obj.addEventListener){ 5             obj.addEventListener(type,fn,false); 6         }else if(obj.attachEvent){ 7             obj.attachEvent(‘on‘+type,fn); 8         } 9     },10     removeEvent:function(obj,type,fn){11         if(obj.removeEventListener){12             obj.removeEvent(type,fn,false);13         }else if(obj.detachEvent){14             obj.detachEvent(‘on‘+type,fn);15         }16     },17     getEvent:function(e){            //获取事件对象18         return e.target|| event.srcElement;19     },20     preventDefault:function(e){     //阻止默认行为;21         if(e.preventDefault){22             e.preventDefault();23         }else{24             e.returnValue=http://www.mamicode.com/false;25         }26     },27     stopPropagation:function(e){     //阻止冒泡;28         if(e.stopPropagation){29             e.stopPropagation();30         }else{31             e.cancelBubble=true;32         }33     },34     clientXY:function(e){ //获取可视范围内的鼠标位置;35         var T=document.documentElement.scrollTop||document.body.scrollTop;36         var L=document.documentElement.scrollLeft||document.body.scrollLeft;37         return {x:L+clientX , y:T+e.clientY};38     },39     getRelatedTarget:function(e){40         if(e.relatedTarget){41             return e.relatedTarget;42         }else if(event.toElement){43             return e.toElement;44         }else if(e.toElement){45             return e.fromElement;46         }else{47             return null;48         }49     },50     getButton:function(e){51         if(document.implementation.hasFeature("MouseEvents","2.0")){52             return e.button;53         }else{54             switch(e.button){55                 case 0:56                 case 1:57                 case 3:58                 case 5:59                 case 7:60                     return 0;61                 case 2:62                 case 6:63                     return 2;64                 case 4:65                     return 1;66             }67         }68     },69     getCharCode:function(e){70         if(typeof event.charCode==‘number‘){71             return e.charCode;72         }else{73             return e.keyCode;74         }75     },76     getWheelDelta:function(e){77         if(e.wheelDelta){78             return (client.engine.opera && client.engine.opera<9.5? -event.wheelDelta :event.wheelDelta);79         }else{80             return -event.detail *40;81         }82     }83 };

 

事件对象库