JavaScript 中的事件冒泡与事件捕获?
事件冒泡 − 无论何时某个元素上发生事件,事件处理程序都会先在其上运行,然后在它的父元素上运行,最后一直跑到它的其他祖先元素上。
事件捕获 − 它与事件冒泡相反,事件会从父元素开始,然后到它的子元素。
以下是 JavaScript 中事件冒泡与事件捕获的代码 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: blueviolet; } .outer { display: inline-block; width: 400px; height: 200px; font-size: 20px; background-color: chartreuse; } .inner { width: 200px; height: 100px; font-size: 20px; background-color: blueviolet; text-align: center; margin: 20px; } .tags { display: inline-block; width: 400px; font-weight: bold; font-size: 18px; } </style> </head> <body> <h1>Event bubbling vs event capturing</h1> <div class="outer"> OUTER <div class="inner">INNER</div> </div> <div class="outer"> OUTER <div class="inner">INNER</div> </div> <br /> <div class="tags">Bubbling</div> <div class="tags">Capturing</div> <div class="result"></div> <script> let outerDiv = document.querySelectorAll(".outer"); let innerDiv = document.querySelectorAll(".inner"); let resEle = document.querySelector(".result"); outerDiv[0].addEventListener("click", () => { resEle.innerHTML += "Outer div has been clicked" + "<br>"; }); innerDiv[0].addEventListener("click", () => { resEle.innerHTML = ""; resEle.innerHTML += "Inner div has been clicked" + "<br>"; }); outerDiv[1].addEventListener("click",() => { resEle.innerHTML = ""; resEle.innerHTML += "Outer div has been clicked" + "<br>"; },true); innerDiv[1].addEventListener("click",() => { resEle.innerHTML += "Inner div has been clicked" + "<br>"; }, true); </script> </body> </html>
输出
点击具有事件冒泡的内部 div −
点击具有事件捕获的内部 div −
广告