Because the ie event is global and firefox event is local, it is not easy to use. At this time, we need to assemble common event operations by ourselves and encapsulate them into classes for reuse.
Copy codeThe Code is as follows:
/**
Class Event
Usage:
Event. getEvent (); get the event of ie and firefox
Event. getTarget (); get srcElement of ie or target of firefox
Event. isIe (); whether it is ie
Event. clientX (); get the x coordinates of ie and fox mouse
Event. clientY (); get y coordinates of ie and fox mouse
*/
Var Event = new function (){
This. toString = function (){
Return this. getEvent ();
}
// Obtain the event
This. getEvent = function (){
Var ev = window. event;
If (! Ev ){
Var c = this. getEvent. caller;
While (c ){
Ev = c. arguments [0];
If (ev & Event = ev. constructor)
Break;
C = c. caller;
}
}
Return ev;
};
// Obtain the event Source
This. getTarget = function (){
Var ev = this. getEvent ();
Return this. isIe ()? Ev. srcElement: ev.tar get;
}
// Whether it is ie
This. isIe = function (){
Return document. all? True: false;
}
// Mouse x coordinate
This. clientX = function (){
Var ev = this. getEvent ();
Var x = this. isIe ()? Ev. clientX: ev. pageX;
Return x;
}
// Y coordinate of the mouse
This. clientY = function (){
Var ev = this. getEvent ();
Var y = this. isIe ()? Ev. clientY: ev. pageY;
Return y;
}
/** Add events (object, event type, function pointer)
Obj: html Object
SEvent: event name
SpNotify: Method of event execution
IsCapture: whether to allow full screen capture
*/
This. addEvent = function (obj, sEvent, fpNotify, isCapture ){
SEvent = sEvent. indexOf ("on ")! =-1? SEvent: "on" + sEvent;
If (obj. addEventListener ){
SEvent = sEvent. substring (sEvent. indexOf ("on") + 2 );
Obj. addEventListener (sEvent, fpNotify, isCapture );
} Else {// ie
If (isCapture)
Obj. setCapture (isCapture );
Obj. attachEvent (sEvent, fpNotify );
}
}
// Remove the event
This. removeEvent = function (obj, sEvent, fpNotify ){
If (obj. removeEventListener ){
SEvent = sEvent. substring (sEvent. indexOf ("on") + 2)
Obj. removeEventListener (sEvent, fpNotify, false );
} Else {
Obj. detachEvent (sEvent, fpNotify );
}
}
// Obtain the mouse buttons, left = 1, middle = 2, right = 3
This. button = function (){
Var ev = this. getEvent ();
If (! Ev. which & ev. button) {// ie
Return ev. button & 1? 1 :( ev. button & 2? 3 :( ev. button & 4? 2: 0 ))
}
Return ev. which;
};
// Prevents event bubbling Transmission
This. stopPropagation = function (){
Var ev = this. getEvent ();
If (this. isIe)
Ev. cancelBubble = true;
Else
Ev. stopPropagation ();
}
// Block the return of default events
This. preventDefault = function (){
Var ev = this. getEvent ();
If (this. isIe)
Ev. returnValue = false;
Else
Ev. preventDefault ();
}
}