15.事件冒泡.html 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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: 500px;
  10. height: 500px;
  11. background: #00f;
  12. }
  13. #box2{
  14. width: 340px;
  15. height: 340px;
  16. background: #0f0;
  17. }
  18. #box3{
  19. width: 200px;
  20. height: 200px;
  21. background: #f00;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <div id="box1">
  27. <div id="box2">
  28. <div id="box3"></div>
  29. </div>
  30. </div>
  31. <script>
  32. var box1 = document.getElementById("box1");
  33. var box2 = document.getElementById("box2");
  34. var box3 = document.getElementById("box3");
  35. box1.onclick = function() {
  36. alert("111")
  37. }
  38. box2.onclick = function(event) {
  39. alert("222")
  40. // 解决事件冒泡
  41. event.stopPropagation();
  42. }
  43. box3.onclick = function(event) {
  44. alert("333")
  45. // IE解决事件冒泡
  46. event.cancelBubble = true;
  47. }
  48. /***
  49. * 事件三个阶段 :
  50. * 捕获 由外到内
  51. * 目标
  52. * 冒泡 由内到外
  53. */
  54. </script>
  55. </body>
  56. </html>