21_DOM_事件机制.html 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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: 600px;
  10. height: 600px;
  11. background-color: blue;
  12. }
  13. .box2{
  14. width: 400px;
  15. height: 400px;
  16. background-color: red;
  17. }
  18. .box3{
  19. width: 200px;
  20. height: 200px;
  21. background-color: green;
  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. <script>
  32. var oBox1 = document.getElementsByClassName("box1")[0];
  33. var oBox2 = document.getElementsByClassName("box2")[0];
  34. var oBox3 = document.getElementsByClassName("box3")[0];
  35. // 事件冒泡 如果多层级元素同时绑定事件那么最内层元素触发事件 事件顺序会由内向外逐层触发
  36. // oBox1.onclick = function(){
  37. // console.log("box1");
  38. // }
  39. // oBox2.onclick = function(){
  40. // console.log("box2");
  41. // }
  42. // oBox3.onclick = function(){
  43. // console.log("box3");
  44. // }
  45. oBox1.addEventListener("click",function(){
  46. console.log("box1");
  47. })
  48. oBox2.addEventListener("click",function(){
  49. console.log("box2");
  50. })
  51. oBox3.addEventListener("click",function(event){
  52. console.log("box3");
  53. // 阻止事件冒泡
  54. event.stopPropagation();
  55. })
  56. // addEventListener 第三个参数为布尔值 默认值为false事件冒泡 true为事件捕获
  57. // 事件捕获 事件触发顺序是由外向内
  58. // oBox1.addEventListener("click",function(){
  59. // console.log("box1");
  60. // },true)
  61. // oBox2.addEventListener("click",function(){
  62. // console.log("box2");
  63. // },true)
  64. // oBox3.addEventListener("click",function(){
  65. // console.log("box3");
  66. // },true)
  67. // 如果同时触发捕获和冒泡那么会先处理捕获事件然后处理冒泡事件
  68. </script>
  69. </body>
  70. </html>