1. Event flow
Event flow describes the order in which events are received from the page. However, what IE proposes is a bubbling stream, while Netscape Communicator proposes a capture stream.
JavaScript event stream
2. Event bubbling
Events are initially received by the most specific element (the node with the deepest nesting level), and then propagate upwards to less specific nodes (documents). As follows:
& Lt; title & gt; incident bubbling & lt;/table & gt;
Click me
window.onload = function(){
var obj = document.getElementById("test");
obj.onclick = function(){
alert(this.tagName);
};
Document.body.onclick = function(){
alert(this.tagName);
};
Document.documentElement.onclick = function(){
alert(this.tagName);
};
Document.onclick = function(){
alert("document");
};
window.onclick = function(){
alert("window");
}
};
Event propagation sequence: div——>body——>html——>document
Note:
All modern browsers support bubbling events, but there are some differences in implementation. Event bubbling in IE5.5 and earlier versions will jump directly from body to document (html will not be executed). Firefox, Chrome, and Safari bubble events all the way to the window object.
3. Stop event bubbling and cancel default events
a. Get the event object
function getEvent(event) {
// window.event IE
// event non-IE
return event || window.event;
}
b Function: Stop event bubbling
function stopBubble(e) {
// If an event object is provided, this is a non-IE browser
if ( e && e.stopPropagation ) {
// Therefore it supports W3C’s stopPropagation() method
e.stopPropagation();
} else {
// Otherwise, we need to use IE to cancel event bubbling
window.event.cancelBubble = true;
}
}
c. Block browser default behavior
function stopDefault( e ) {
// Block default browser actions (W3C)
If ( e && e.preventDefault ) {
e.preventDefault();
} else {
//How to prevent the default action of function in IE
window.event.returnValue = false;
}
Return false;
}
Statement: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