16.事件冒泡.html 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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: 700px;
  10. height: 700px;
  11. background: #f00;
  12. }
  13. #box2 {
  14. width: 350px;
  15. height: 350px;
  16. background: #ff0;
  17. }
  18. #box3 {
  19. width: 175px;
  20. height: 175px;
  21. background: #0f0;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <!--
  27. 事件三个阶段:
  28. 事件捕获:由外向内
  29. 目标阶段
  30. 事件冒泡:由内向外
  31. -->
  32. <div id="box1">
  33. <div id="box2">
  34. <div id="box3"></div>
  35. </div>
  36. </div>
  37. <script>
  38. var box1 = document.getElementById("box1")
  39. var box2 = document.getElementById("box2")
  40. var box3 = document.getElementById("box3")
  41. // box1.onclick = function() {
  42. // console.log("1")
  43. // }
  44. // box2.onclick = function(event) {
  45. // console.log("2");
  46. // // 阻止事件冒泡
  47. // event.stopPropagation();
  48. // }
  49. // box3.onclick = function(event) {
  50. // console.log("3")
  51. // // 阻止事件冒泡
  52. // event.cancelBubble = true;
  53. // }
  54. /**
  55. * 监听事件
  56. * xxx.addEventListener('mousemove',function() {xxxx},true/false)
  57. * true 捕获
  58. * false 冒泡
  59. */
  60. box1.addEventListener('click',function() {
  61. console.log(1);
  62. },false)
  63. box2.addEventListener('click',function() {
  64. console.log(2);
  65. },false)
  66. box3.addEventListener('click',function() {
  67. console.log(3);
  68. },false)
  69. </script>
  70. </body>
  71. </html>