dom event bubbling mechanism
Bubbling: After the html element triggers the event, the event will bubble up, hand it over to the parent element for processing, and then upwards in turn until the browser window window
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#pre {
width: 200px;
height: 200px;
background: #31fdff;
}
#child {
width: 100px;
height: 100px;
background: #bfa;
}
</style>
</head>
<body>
<div id="pre">
<div id="child"></div>
</div>
<script>
document.getElementById('pre').addEventListener('click', function (e) {
console.log('pre');
})
document.getElementById('child').addEventListener('click', function (e) {
console.log('child');
})
window.addEventListener('click', function (e) {
console.log('window');
})
</script>
</body>
</html>
Click the child element, the console prints the result
Bubbling path
Event.composedPath() returns a list of element objects that handle the event, the first element is the first element that triggered the event, and the last is the window object
Example
document.getElementById('pre').addEventListener('click', function (e) {
console.log('pre');
console.log(e.composedPath());
})
document.getElementById('child').addEventListener('click', function (e) {
console.log('child');
console.log(e.composedPath());
})
window.addEventListener('click', function (e) {
console.log('window');
console.log(e.composedPath());
})
Click the child element, the console prints the result
Block events from bubbling up
Event.stopPropagation() blocks the event from bubbling to the parent element. After the current element is processed, the parent element no longer triggers the event
document.getElementById('pre').addEventListener('click', function (e) {
console.log('pre');
console.log(e.composedPath());
})
document.getElementById('child').addEventListener('click', function (e) {
// 阻断事件向上冒泡
e.stopPropagation()
console.log('child');
})
window.addEventListener('click', function (e) {
console.log('window');
console.log(e.composedPath());
})
Click the child element, the console prints the result
Block event triggered at the same level
For example, if two click event handlers are registered for the same element, if the propagation of the event is blocked in the first registered event handler, then the second registered event handler will no longer trigger
non-blocking statistics events Trigger example
document.getElementById('child').addEventListener('click', function (e) {
console.log('child 1');
})
document.getElementById('child').addEventListener('click', function (e) {
console.log('child 2');
})
Click the child element, the console prints the result
Example of blocking statistics event triggering
document.getElementById('child').addEventListener('click', function (e) {
e.stopImmediatePropagation()
console.log('child 1');
})
document.getElementById('child').addEventListener('click', function (e) {
console.log('child 2');
})
Click the child element, the console prints the result