16_DOM事件机制.html 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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("4-box1")
  38. },false)
  39. oBox2.addEventListener("click",function(e){
  40. console.log("3-box2")
  41. // 阻止事件冒泡
  42. e.stopPropagation();
  43. },false)
  44. // 事件捕获
  45. // 事件捕获:事件从文档的根元素(html标签)开始,然后逐步向下捕获到触发事件的元素,直到到达目标元素。
  46. // 事件捕获的过程中,事件处理函数会按照元素的层级关系,从外到内依次执行。
  47. // oBox1.addEventListener("click",function(){
  48. // console.log("1-box1")
  49. // },true)
  50. // oBox2.addEventListener("click",function(){
  51. // console.log("2-box2")
  52. // },true)
  53. </script>
  54. </body>
  55. </html>