Home > Web Front-end > JS Tutorial > Introduction to cross-browser event objects_javascript skills

Introduction to cross-browser event objects_javascript skills

WBOY
Release: 2016-05-16 17:52:18
Original
1171 people have browsed it
Copy code The code is 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 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.
Copy code The code is as follows:

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){
alert("Clicked "); event = EventUtil.getEvent(event); EventUtil.stopPropagation(event); }; document.body.onclick = function(event){ alert(" Body clicked"); };

Remember that this method may block the event in the browser's bubbling phase or both the browser's bubbling and capturing phases.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template