Although the IE event object is different from the DOM Event object, the information and capabilities contained in the IE event object are the same as those of the DOM Event object, only in different forms, by ing, we can implement event objects compatible with IE and DOM Event objects.
The Code is as follows:
Var eventUtil = {
GetEvent: function (event ){
Return event? Event: window. event;
};
GetTarget: function (event ){
Return event.tar get | 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 a DOM-compatible browser is used, the event variable is passed in and is returned. In IE, the event parameter is undefined, So window. event will be returned, so eventUtil is used. the getEvent () method is available in both dom and IE.
Similarly, in the second method, the getTarge () method first detects the target attribute of the event object. If the target attribute exists, the system returns the targe attribute. If the target attribute is an IE browser, the system returns the srcElement attribute. Ensure compatibility.
The Code is as follows:
Btn. onclick = function (event ){
Event = EventUtil. getEvent (event );
Var target = EventUtil. getTarget (event );
};
The third method is the preventDefault () method. When the event object is passed in, it first checks whether the preventDefault () method of the event object is available. If it is available, the preventDefault method is called, if not, set the returnValue of the event to false.
For example:
The Code is 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 tag. The event object comes from the return value of the getEvent method of EventUtil and serves as the input parameter of the preventDefault () method.
The fourth method is stopPropagation (). In the same way, first try the DOM method, and then try the cancelBubble attribute, for example, the following code:
The Code is 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 being in the bubble or capture phase of the browser.