02.冒泡.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. #box1 {
  10. width: 200px;
  11. height: 200px;
  12. background-color: yellowgreen;
  13. }
  14. #s1 {
  15. background-color: yellow;
  16. }
  17. </style>
  18. <script>
  19. window.onload = function () {
  20. /**
  21. * 事件的冒泡(Bubble)
  22. * -所谓的冒泡指的就是事件向上传导,当后代元素上的事件被触发时,
  23. * 其祖先元素的相同事件也会被触发
  24. * -在开发中大部分情况冒泡都是有用的,如果不希望发生事件冒泡,
  25. * 可以通过事件对象来取消冒泡
  26. */
  27. //为s1绑定一个单击响应函数
  28. var s1 = document.getElementById("s1");
  29. s1.onclick = function (event) {
  30. event = event || window.event;
  31. alert("span的单击响应函数");
  32. //取消冒泡
  33. //可以将事件对象的cancelBubble设置为true,即可取消冒泡
  34. event.cancelBubble = true;
  35. };
  36. //为box1绑定一个单击响应函数
  37. var box1 = document.getElementById("box1");
  38. box1.onclick = function () {
  39. alert("div的单击响应函数");
  40. event.cancelBubble = true;
  41. };
  42. //为body绑定一个单击响应函数
  43. document.body.onclick = function(){
  44. alert('body的单击响应函数');
  45. };
  46. };
  47. </script>
  48. </head>
  49. <body>
  50. <div id="box1">
  51. 我是box1
  52. <span id="s1">我是span</span>
  53. </div>
  54. </body>
  55. </html>