example05.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. <style>
  7. #one {
  8. width: 400px;
  9. height: 400px;
  10. background-color: indianred;
  11. margin: 60px auto;
  12. }
  13. #two {
  14. width: 300px;
  15. height: 300px;
  16. background-color: darkseagreen;
  17. }
  18. #three {
  19. width: 200px;
  20. height: 200px;
  21. background-color: lightsteelblue;
  22. }
  23. #two, #three {
  24. position: relative;
  25. left: 50px;
  26. top: 50px;
  27. }
  28. </style>
  29. </head>
  30. <body>
  31. <div id="one">
  32. <div id="two">
  33. <div id="three"></div>
  34. </div>
  35. </div>
  36. <script>
  37. var one = document.querySelector('#one');
  38. var two = document.querySelector('#two');
  39. var three = document.querySelector('#three');
  40. // addEventListener方法的第一个参数是事件名
  41. // 第二个参数是事件发生时需要执行的回调函数
  42. // 第三个参数是一个布尔值
  43. // 如果是true表示事件捕获 - 从外层向内层传递事件
  44. // 如果是false表示事件冒泡 - 从内存向外层传递事件
  45. // 一般情况下事件处理的方式都是事件冒泡(默认行为)
  46. // 如果想阻止事件的传播行为可以调用事件对象的stopPropagation方法
  47. one.addEventListener('click', function() {
  48. window.alert('I am one!');
  49. });
  50. two.addEventListener('click', function() {
  51. window.alert('I am two!');
  52. });
  53. // 事件回调函数中的第一个参数是事件对象(封装了和事件相关的信息)
  54. three.addEventListener('click', function(evt) {
  55. window.alert('I am three!');
  56. evt.stopPropagation();
  57. });
  58. </script>
  59. </body>
  60. </html>