Without too much introduction, directly on the dry goods, first of all, we first write out the overall style structure
structure
<style>
.father {
width: 500px;
height: 500px;
background: black;
}
.son {
width: 250px;
height: 250px;
background: yellow;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
Copy the code
The effect
1. Events bubble up
<script>
let father = document.querySelector('.father')
let son = document.querySelector('.son')
father.addEventListener('click',()=>{
console.log('father');
})
son.addEventListener('click',(e)=>{
console.log('son');
})
</script>
Copy the code
When clicking on the part of the child box that is common to both the parent box and the parent box, a phenomenon called event bubbling will occur. Both the parent box and the parent box will register the events and print out the results:
It turns out that when you click on the child box the event of the parent box is also triggered, so why is it called bubble because the child box is inside the parent box and it’s bubbling out, so it’s called bubble.
To prevent a bubble
The effect of preventing bubbling is achieved through the event parameter E. topPropagation method
son.addEventListener('click',(e)=>{
e.stopPropagation()
console.log('son');
})
Copy the code
This is easy if it is vue:
< button@click. stop="hClick"></button>Copy the code
2. Event capture
Event capturing can only be done with the third argument to addEventListener, false if not written, or true if event capturing is enabled, continue clicking on the same section with the following code.
let father = document.querySelector('.father')
let son = document.querySelector('.son')
father.addEventListener('click',()=>{
console.log('father');
},true)
son.addEventListener('click',(e)=>{
console.log('son');
})
Copy the code
Capture is the opposite of bubbling, passing events from the outside in. Note that onclick does not capture events, only the third parameter of addEventListener does this manually.
3. Event delegation
If an element is dynamically created and you want to register an event for that element, then you must use the delegate, register the ul click event e.target, and get each li:
The < body > < ul > < li > 1 li < / li > < li > second li < / li > < li > third li < / li > < li > fourth li < / li > < / ul > < script > / / event capture the let ul = document.querySelector('ul'); ul.addEventListener('click', function (e) { console.log(e.target.innerText); }) </script> </body>Copy the code
Today has to share here, as a front-end primary school, welcome you to teach