<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>test</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        position: relative;
      }
      .box2 {
        height: 50px;
        width: 150px;
        background: blue;
        position: absolute;
        top: 0px;
        left: 0px;
      }
      .box1 {
        height: 50px;
        width: 200px;
        background: red;
        position: absolute;
        top: 0px;
        left: 50px;
      }
    </style>
  </head>
  <body>
    <div class="box1">
      <div class="box2"></div>
    </div>

    <script>
      const box1 = document.querySelector(".box1");
      const box2 = document.querySelector(".box2");
      box1.addEventListener(
        "click",
        (e) => {
          e.stopPropagation();
          console.log("box1");
        },
        true
      );
      box2.addEventListener(
        "click",
        (e) => {
          e.stopPropagation();
          console.log("box2");
        },
        false
      );
    </script>
  </body>
</html>

事件冒泡: 点击事件由子元素向父元素传递 即 先调用子元素的点击事件再调用父元素的点击事件

注意点:浏览器默认采用事件冒泡,即 不用做任何特殊设置,给元素添加点击事件后,点击元素,浏览器先调用子元素的方法,再调用父元素的方法

事件捕获: 点击事件由父元素向子元素传递,即 先调用父元素的点击事件再调用子元素的点击事件

注意点:需要设置addEventListener的第三个参数为true才能开启事件捕获, 给元素添加点击事件并设置捕获后,点击元素,浏览器先调用父元素的方法,再调用子元素的方法

同时需要注意: 如果父元素设置为事件捕获子元素同时设置为事件冒泡,那么会先按照事件捕获进行处理 父元素的点击事件被调用 如果父元素没有阻止传递,则继续调用子元素的方法

 

 posted on 2024-02-08 11:53  laremehpe  阅读(14)  评论(0编辑  收藏  举报