事件冒泡与事件捕获的作用与区别

首先了解什么是冒泡事件与捕获事件

冒泡事件:是指子元素向父元素传递的过程
捕获事件:是指父元素向子元素传递的过程

<style> 
  div {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  #box1 {
    height: 150px;
    background-color: red;
   
  }
  #box2 {
     80%;
    height: 100px;
    background-color: yellow;
  }
  #box3 {
     80%;
    height: 50px;
    background-color: green;
  }
</style>
<body>
  <div id="box1">
    <div id="box2">
      <div id="box3"></div>
    </div>
  </div>
</body>
</html>
<script  type="text/javascript">
  var box1 = document.getElementById("box1");
  var box2 = document.getElementById("box2");
  var box3 = document.getElementById("box3");
  // addEventListener 事件默认为false,也就是我们所说的事件冒泡过程
  box1.addEventListener('click', function(){
    alert("box1 被触发了");
  })

  box2.addEventListener('click', function(){
    alert("box2 被触发了");
  })

  box3.addEventListener('click', function(){
    alert("box3 被触发了");
  })

  // 点击box3打印结果
  // box3 
  // box2
  // box1
  
  // 当我们将 addEventListener 设置为true时,此时就成了事件捕获的过程
  box1.addEventListener('click', function(){
    alert("box1 被触发了");
  }, true)

  box2.addEventListener('click', function(){
    alert("box2 被触发了");
  }, true)

  box3.addEventListener('click', function(){
    alert("box3 被触发了");
  })

  // 点击box3打印结果
  // box1 
  // box2
  // box3

  // 阻止事件冒泡
  box1.addEventListener('click', function(){
    alert("box1 被触发了");
  })

  box2.addEventListener('click', function(event){
    alert("box2 被触发了");
    event.stopPropagation();
  })

  box3.addEventListener('click', function(){
    alert("box3 被触发了");
  })

  // 点击box3打印结果
  // box3
  // box2
  
  // 阻止事件捕获
  box1.addEventListener('click', function(){
    alert("box1 被触发了");
  }, true)

  box2.addEventListener('click', function(event){
    alert("box2 被触发了");
    event.stopPropagation();
  }, true)

  box3.addEventListener('click', function(){
    alert("box3 被触发了");
  })

  // 点击box3打印结果
  // box1
  // box2

</script>

 

原文地址:https://www.cnblogs.com/fczbk/p/13607188.html