19.事件冒泡.html 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. <style>
  8. .box1 {
  9. width: 500px;
  10. height: 500px;
  11. background: #f00;
  12. }
  13. .box2 {
  14. width: 300px;
  15. height: 300px;
  16. background: #ff0;
  17. }
  18. .box3 {
  19. width: 150px;
  20. height: 150px;
  21. background: #00f;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <div class="box1">
  27. <div class="box2">
  28. <div class="box3"></div>
  29. </div>
  30. </div>
  31. <!--
  32. 事件的三个阶段:
  33. 事件捕获:由外向内触发的操作
  34. 目标阶段
  35. 事件冒泡:由内向外触发的操作
  36. 阻止事件冒泡:
  37. event.stopPropagation()
  38. IE浏览器阻止事件冒泡
  39. event.cancelBubble = true
  40. -->
  41. <script>
  42. var box1 = document.querySelector(".box1");
  43. var box2 = document.querySelector(".box2");
  44. var box3 = document.querySelector(".box3");
  45. // box1.onclick = function(eve) {
  46. // eve.cancelBubble = true;
  47. // alert("这是第一个");
  48. // }
  49. // box2.onclick = function(eve) {
  50. // eve.stopPropagation();
  51. // alert("这是第二个");
  52. // }
  53. // box3.onclick = function(event) {
  54. // event.cancelBubble = true;
  55. // alert("这是第三个");
  56. // }
  57. // 填加监听事件
  58. // xxx.addEventListener('监听的时间方法',执行的函数,触发的事件类型:true (事件捕获) / false(事件冒泡))
  59. box1.addEventListener(
  60. "click",
  61. function (eve) {
  62. eve.stopPropagation();
  63. alert("内容1");
  64. },
  65. false
  66. );
  67. box2.addEventListener(
  68. "click",
  69. function (eve) {
  70. eve.cancelBubble = true;
  71. alert("内容2");
  72. },
  73. false
  74. );
  75. box3.addEventListener(
  76. "click",
  77. function (eve) {
  78. eve.stopPropagation();
  79. alert("内容3");
  80. },
  81. false
  82. );
  83. </script>
  84. </body>
  85. </html>