example07.html 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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: red;
  11. }
  12. #two {
  13. width: 300px;
  14. height: 300px;
  15. background-color: green;
  16. }
  17. #three {
  18. width: 200px;
  19. height: 200px;
  20. background-color: blue;
  21. }
  22. #two, #three {
  23. position: relative;
  24. left: 50px;
  25. top: 50px;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <div id="one">
  31. <div id="two">
  32. <div id="three"></div>
  33. </div>
  34. </div>
  35. <script>
  36. (function() {
  37. function f1(evt) {
  38. alert('I am one');
  39. }
  40. function f2() {
  41. alert('I am two');
  42. }
  43. function f3(evt) {
  44. alert('I am three');
  45. evt = evt || window.event;
  46. // 阻止事件传播行为(冒泡或捕获)
  47. if (evt.stopPropagation) {
  48. evt.stopPropagation();
  49. } else {
  50. evt.cancelBubble = true;
  51. }
  52. }
  53. // 要么是全局作用域 要么是函数级作用域
  54. // 事件捕获 - 从外层向内层传递事件的过程
  55. // 事件冒泡 - 从内层向外层传递事件的过程(默认)
  56. // 内嵌的元素在响应事件之后会继续将事件传递到它的父元素
  57. var fs = [f1, f2, f3];
  58. var ids = ['one', 'two', 'three'];
  59. for (var i = 0; i < ids.length; i += 1) {
  60. var div = document.getElementById(ids[i]);
  61. if (div.addEventListener) {
  62. // 如果需要使用事件捕获可以传入第三个参数并赋值为true
  63. div.addEventListener('click', fs[i]);
  64. } else {
  65. div.attachEvent('onclick', fs[i]);
  66. }
  67. }
  68. })();
  69. </script>
  70. </body>
  71. </html>