10
0

21_DOM事件机制.html 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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: 400px;
  10. height: 400px;
  11. background-color:red;
  12. }
  13. .box2{
  14. width: 200px;
  15. height: 200px;
  16. background-color:blue;
  17. }
  18. .box3{
  19. width: 100px;
  20. height: 100px;
  21. background-color: yellow;
  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 oBxo1 = document.getElementsByClassName("box1")[0];
  33. var oBxo2 = document.getElementsByClassName("box2")[0];
  34. var oBox3 = document.getElementsByClassName("box3")[0];
  35. // 事件机制 冒泡
  36. // oBxo1.onclick = function(){
  37. // console.log("box1");
  38. // }
  39. // oBxo2.onclick = function(){
  40. // console.log("box2");
  41. // }
  42. // oBox3.onclick = function(){
  43. // console.log("box3");
  44. // }
  45. // js事件机制分为 事件捕获 事件冒泡
  46. // 事件捕获由外向内逐层触发 addEventListener 第三个参数为true
  47. // 事件冒泡由内向外逐层触发 addEventListener 第三个参数为false
  48. // js事件机制的顺序
  49. oBxo1.addEventListener("click",function(){
  50. console.log("box1");
  51. },false)
  52. oBxo2.addEventListener("click",function(){
  53. console.log("box2");
  54. },false)
  55. oBox3.addEventListener("click",function(){
  56. console.log("box3");
  57. },false)
  58. oBxo1.addEventListener("click",function(){
  59. console.log("box1");
  60. },true)
  61. oBxo2.addEventListener("click",function(){
  62. console.log("box2");
  63. },true)
  64. oBox3.addEventListener("click",function(){
  65. console.log("box3");
  66. },true)
  67. </script>
  68. </body>
  69. </html>