首页 > 代码库 > 事件冒泡(event bubbling)和事件捕获(event capturing)

事件冒泡(event bubbling)和事件捕获(event capturing)

事件冒泡时,触发click事件:

 1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4     <meta charset="UTF-8"> 5     <title>Bubble Test</title> 6 </head> 7 <body> 8     <div id="myDiv">Div</div> 9 </body>10 <script>11     window.addEventListener(click, function () {12         alert(window);13     },false);14     document.addEventListener(click, function () {15         alert(document);16     },false);17     document.childNodes[1].addEventListener(click, function () {18         alert(html);19     },false);20     document.body.addEventListener(click, function () {21         alert(body);22     },false);23     document.getElementById(myDiv).addEventListener(click, function () {24         alert(myDiv);25     },false);26 </script>27 </html>

事件捕获时,触发click事件:

 1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4     <meta charset="UTF-8"> 5     <title>Bubble Test</title> 6 </head> 7 <body> 8     <div id="myDiv">Div</div> 9 </body>10 <script>11     window.addEventListener(click, function () {12         alert(window);13     },true);14     document.addEventListener(click, function () {15         alert(document);16     },true);17     document.childNodes[1].addEventListener(click, function () {18         alert(html);19     },true);20     document.body.addEventListener(click, function () {21         alert(body);22     },true);23     document.getElementById(myDiv).addEventListener(click, function () {24         alert(myDiv);25     },true);26 </script>27 </html>

 

事件冒泡(event bubbling)和事件捕获(event capturing)