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 compatible browser, the event variable is simply passed in and returned. In IE the event parameter will be undefined, so window.event will be Return, so the event return value is available whether on DOM or IE using the eventUtil.getEvent() method.
Similarly to the second method, the getTarge() method, first detects the target attribute of the event object. If it exists, it returns the target attribute. If it is an IE browser, it returns the srcElement attribute. Compatibility guaranteed.
btn.onclick = function(event){
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
};
The third method, preventDefault () method, when the event object is passed When entering, first check whether the preventDefault() method of the event object is available. If it is available, call the preventDefault method. If it is not available, set the returnValue of the event to false.
For example:
.getElementById("myLink");
link.onclick = function(event){
event = EventUtil.getEvent(event);
EventUtil.preventDefault(event); }; This code prevents the default behavior of a link tag. The event object comes from the return value of the getEvent method of EventUtil and is used as the incoming parameter of the preventDefault() method. The fourth method, stopPropagation(), uses the same method, first try the DOM method, and then try the cancelBubble attribute, such as the following code:
Copy code
The code is as follows:
var btn = document.getElementById("myBtn");
btn.onclick = function(event){
Remember that this method may block the event in the browser's bubbling phase or both the browser's bubbling and capturing phases.