1. Event flow
Event streams describe the order in which events are received from the page. But IE proposes bubble streams, while Netscape Communicator proposes capture streams.
JavaScript event stream
2. Event bubble
The event begins to be received by the most specific element (the node with the deepest nesting hierarchy), and then propagates upward step by step to less specific nodes (document). as follows:
The code copy is as follows:
<html>
<head>
<title>Event bubbling</title>
</head>
<body>
<div id="myDiv">Click me</div>
</body>
</html>
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 order: div->body->html->document
Notice:
All modern browsers support bubble events, but there are some differences in implementation. Event bubbles in IE5.5 and earlier versions will jump directly from body to document (no html is executed). Firefox, Chrome, and Safari bubble events all the way to the window object.
3. Stop event bubbles and cancel default events
a. Get the event object
The code copy is as follows:
function getEvent(event) {
// window.event IE
// event non-IE
return event || window.event;
}
b Function: Stop event bubbles
The code copy is as follows:
function stopBubble(e) {
// If an event object is provided, this is a non-IE browser
if ( e && e.stopPropagation ) {
// Therefore it supports the stopPropagation() method of W3C
e.stopPropagation();
} else {
// Otherwise, we need to use IE to cancel the event bubble
window.event.cancelBubble = true;
}
}
c. Block the default behavior of the browser
The code copy is as follows:
function stopDefault( e ) {
// Block default browser action (W3C)
if ( e && e.preventDefault ) {
e.preventDefault();
} else {
// How to block the default action of the function in IE
window.event.returnValue = false;
}
return false;
}