First create two boxes and add click events to them, as shown below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .father{ margin: 100px auto; width: 100px; height:100px; overflow: hidden; background-color: palegreen; } .son{ width: 50px; height: 50px; margin-left: 25px; margin-top: 25px; background-color: paleturquoise; } </style> </head> <body> <div class="father"> <div class="son"></div> </div> <script> var father = document.querySelector('.father'); var son = document.querySelector('.son'); son.addEventListener('click',function(){ alert('son'); },false) father.addEventListener('click',function(){ alert('father'); },false) </script> </body> </html> When we click on the click event of the child box, the print result is: How should we block the click event of the parent box? You can add As shown below: son.addEventListener('click',function(e){ alert('son'); e.stopPropagation(); },false) At this point, the running result is: Blocking success.
e.cancelBubble = true; If we want to solve this compatibility problem, we can use the following method: if(e && e.stopPropagation){ e.stopPropagation(); }else{ window.event.cancelBubble = true; } This is the end of this article about preventing event bubbling based on JavaScript. For more relevant content about preventing event bubbling based on JavaScript, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: After reading the introduction of CSS box model, you will not be confused
>>: HTML code text box limit input text box becomes gray limit text box input
Table of contents Pull the image Run the image (g...
background Recently, I executed a DML statement d...
This article shares the specific code of js to ac...
<br />First think of the idea, then draw a s...
Table of contents 1. Anti-shake function 2. Use d...
ReactRouter implementation ReactRouter is the cor...
This article example shares the specific code of ...
1. Command Introduction The passwd command is use...
This article shares the specific code of Vue3 man...
1. Install the express library and generator Open...
This article example shares the specific code of ...
Why does CSS have a cascading mechanism? Because ...
I believe that many users who make websites will ...
1. scale() method Zoom refers to "reducing&q...
Database performance optimization generally adopt...