12_js事件.html 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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: 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. // 事件冒泡 当有多个元素嵌套的时候 并且绑定相同事件当内层元素触发事件的时候 会逐层触发外层元素的事件
  33. var oBox1 = document.getElementsByClassName("box1")[0];
  34. var oBox2 = document.getElementsByClassName("box2")[0];
  35. var oBox3 = document.getElementsByClassName("box3")[0];
  36. oBox1.onclick = function(){
  37. console.log("box1");
  38. }
  39. oBox2.onclick = function(){
  40. console.log("box2");
  41. }
  42. oBox3.onclick = function(e){
  43. console.log("box3");
  44. // 阻止事件冒泡
  45. e.stopPropagation();
  46. }
  47. </script>
  48. </body>
  49. </html>