JS has a variety of event objects, compatibility is uneven, this object encapsulates most of the required methods
varEventutil={addhandler:function (element,type,handler) {//Add Event if(Element.addeventlistener) {Element.addeventlistener (Type,handler,false);//adding events using the DOM2-level method}Else if(element.attachevent) {//add an event using the IE methodElement.attachevent (" on"+Type,handler); }Else{element[" on"+type]=handler;//adding events using the DOM0-level method}}, Removehandler:function (Element,type,handler) {//Cancel Event if(Element.removeeventlistener) {Element.removeeventlistener (Type,handler,false); }Else if(element.detachevent) {element.detachevent (" on"+Type,handler); }Else{element[" on"+type]=NULL; }}, Getevent:function (Event){//Use this method to get the event object across browsers return Event?Event: Window.Event; }, Gettarget:function (Event){//returns the actual destination of the event return Event. target| |Event. srcelement; }, Preventdefault:function (Event){//default behavior for blocking events if(Event. Preventdefault) { Event. Preventdefault (); }Else{ Event. returnvalue=false; }}, Stoppropagation:function (Event){//immediately stop the propagation of events in the DOM//avoid triggering event handlers that are registered on Document.body if(Event. Stoppropagation) { Event. Stoppropagation (); }Else{ Event. cancelbubble=true; }}, Getrelatedtarget:function (Event){//get mouseover and mouseout related elements if(Event. Relatedtarget) { return Event. Relatedtarget; }Else if(Event. toelement) {//compatible with ie8- return Event. toelement; }Else if(Event. FormElement) { return Event. FormElement; }Else{ return NULL; }}, Getbutton:function (Event){//gets whether the button pressed or released by MouseDown or MouseUp is in the mouse if(Document.implementation.hasFeature ("mouseevents","2.0")){ return Event. Button; }Else{ Switch(Event. button) {//Map the button property under the IE model to the Button property under the DOM model Case 0: Case 1: Case 3: Case 5: Case 7: return 0;//The main mouse button is pressed (usually left) Case 2: Case 6: return 2;//The middle mouse button is pressed Case 4: return 1;//mouse button (usually right button)}}, Getwheeldelta:function (Event){//Gets the value that represents the scroll direction of the mouse wheel if(Event. Wheeldelta) { return Event. Wheeldelta; }Else{ return-Event. detail* +; }}, Getcharcode:function (Event){//to get the same character encoding across browsers, using the KeyPress event if(typeof Event. charcode==" Number"){ return Event. CharCode; }Else{ return Event. keycode; } } };
JavaScript Event Object Eventutil