16_DOM事件机制.html 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. </style>
  19. </head>
  20. <body>
  21. <div class="box1">
  22. <div class="box2"></div>
  23. </div>
  24. <script>
  25. var oBox1 = document.getElementsByClassName("box1")[0];
  26. var oBox2 = document.getElementsByClassName("box2")[0];
  27. // 事件冒泡
  28. // 事件冒泡:事件从最当前触发事件的元素开始,然后逐步向上冒泡到祖先元素,直到到达文档的根元素(html标签)。
  29. // 事件冒泡的过程中,事件处理函数会按照元素的层级关系,从内到外依次执行。
  30. // oBox1.onclick = function(){
  31. // console.log("box1")
  32. // }
  33. // oBox2.onclick = function(){
  34. // console.log("box2")
  35. // }
  36. oBox1.addEventListener("click",function(){
  37. console.log("3-box1")
  38. },false)
  39. oBox2.addEventListener("click",function(){
  40. console.log("4-box2")
  41. },false)
  42. oBox1.addEventListener("click",function(){
  43. console.log("1-box1")
  44. },true)
  45. oBox2.addEventListener("click",function(){
  46. console.log("2-box2")
  47. },true)
  48. </script>
  49. </body>
  50. </html>