13.事件冒泡.html 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. div {
  9. margin-top: 20px;
  10. }
  11. #box1 {
  12. width: 600px;
  13. height: 600px;
  14. background-color: red;
  15. }
  16. #box2 {
  17. width: 400px;
  18. height: 400px;
  19. background-color: green;
  20. }
  21. #box3 {
  22. width: 200px;
  23. height: 200px;
  24. background-color: blue;
  25. }
  26. </style>
  27. </head>
  28. <body>
  29. <!--
  30. 事件:
  31. 事件捕获 由外向内
  32. 目标阶段
  33. 事件冒泡 由内向外
  34. -->
  35. <div id="box1">
  36. <div id="box2">
  37. <div id="box3"></div>
  38. </div>
  39. </div>
  40. <script>
  41. var box1 = document.getElementById("box1");
  42. var box2 = document.getElementById("box2");
  43. var box3 = document.getElementById("box3");
  44. // box1.onclick = function(event) {
  45. // console.log(event)
  46. // // 取消冒泡事件方法
  47. // event.stopPropagation();
  48. // alert("box1")
  49. // }
  50. // box2.onclick = function(event) {
  51. // alert("box2")
  52. // // IE浏览器
  53. // event.cancelBubble = true
  54. // // event.stopPropagation();
  55. // }
  56. // box3.onclick = function(event) {
  57. // alert("box3")
  58. // event.stopPropagation();
  59. // }
  60. // 添加监听事件
  61. // xxx.addEventListener(事件类型,执行的函数,开启事件类别<true 事件捕获/false 事件冒泡>)
  62. // xxx.removeEventListener...
  63. box1.addEventListener('click',function(){
  64. console.log("1111")
  65. },false)
  66. box2.addEventListener('click',function(){
  67. console.log("222")
  68. event.stopPropagation();
  69. },false)
  70. box3.addEventListener('click',function(){
  71. console.log("333")
  72. event.stopPropagation();
  73. },false)
  74. </script>
  75. </body>
  76. </html>