Copy Code code as follows:
var eventutil = {
Getevent:function (event) {
Return event? Event:window.event;
};
Gettarget:function (event) {
return Event.target | | Event.srcelement;
};
Preventdefault:function (event) {
if (Event.preventdefault) {
Event.preventdefault ();
}else{
Event.returnvalue = false;
}
};
Stoppropagation:function (event) {
if (event.stoppropagation) {
Event.stoppropagation ();
}else{
Event.cancelbubble = true;
}
};
};
When using a DOM-compliant browser, the event variable is simply passed in and returned, and the event parameter in IE will be undefined, so the window.event will be returned, so use Eventutil.getevent () Method The event return value is available either on DOM or ie.
Similarly, the second method, the Gettarge () method, first detects the target property of the event object and, if it exists, returns Targe, and returns the Srcelement property for IE browser. ensure compatibility.
Copy Code code as follows:
Btn.onclick = function (event) {
event = Eventutil.getevent (event);
var target = Eventutil.gettarget (event);
};
The third method, the Preventdefault () method, detects whether the Preventdefault () method of the event object is available when the event object is passed in, and then calls the Preventdefault method if available. Set the returnvalue of the event to false if it is not available.
For example:
Copy Code code as follows:
var link = document.getElementById ("MyLink");
Link.onclick = function (event) {
event = Eventutil.getevent (event);
Eventutil.preventdefault (event);
};
This code blocks the default behavior of a link label, which comes from the return value of the Eventutil GetEvent method and as an incoming parameter to the Preventdefault () method.
The fourth Method Stoppropagation (), in the same way, first tries the DOM method, and then attempts to cancelbubble the property, such as the following code:
Copy Code code as follows:
var btn = document.getElementById ("mybtn");
Btn.onclick = function (event) {
Alert ("clicked");
event = Eventutil.getevent (event);
Eventutil.stoppropagation (event);
};
Document.body.onclick = function (event) {
Alert ("Body clicked");
};
Remember that this method may prevent events from bubbling in the browser or at the same time blocking events in the browser's bubbling and capturing stages.