5.事件冒泡.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var box1 = document.getElementById("box1");
  2. var box2 = document.getElementById("box2");
  3. var box3 = document.getElementById("box3");
  4. // 事件捕获 由外向内触发操作
  5. // 事件冒泡 由内向外触发操作
  6. // box1.onclick = function(event) {
  7. // console.log("第一个盒子");
  8. // event.stopPropagation();
  9. // }
  10. // box2.onclick = function(event) {
  11. // console.log("第二个盒子");
  12. // event.stopPropagation();
  13. // }
  14. // box3.onclick = function(event) {
  15. // console.log("第三个盒子");
  16. // // IE浏览器阻止事件冒泡方法
  17. // event.cancelBubble = true;
  18. // }
  19. // 阻止事件冒泡
  20. // 1.event.stopPropagation();
  21. //2.event.cancelBubble = true;
  22. // addEventListener 添加监听事件
  23. // 1.要执行的事件 字符串格式
  24. // 2.执行的函数方法
  25. // 3.触发类型 false(事件冒泡) true(事件捕获)
  26. box1.addEventListener("click",function(event){
  27. console.log("第一个盒子");
  28. event.stopPropagation();
  29. },false);
  30. box2.addEventListener("click",function(event){
  31. console.log("第二个盒子");
  32. event.stopPropagation();
  33. },false);
  34. box3.addEventListener("click",function(event){
  35. console.log("第三个盒子");
  36. event.cancelBubble = true;
  37. },false);