1.冒泡事件

点击子级元素节点触发事件,也会触发父级的事件就是事件冒泡

如何阻止事件冒泡:

在相应的节点事件函数内使用 :event.stopPropagation()

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    #box {
      display: flex;
      width: 800px;
      height: 800px;
      background: red;
    }
    #box1 {
      margin: auto;
      width: 500px;
      height: 500px;
      background: green;
      display: flex;
    }
    #box2 {
      margin: auto;
      width: 300px;
      height: 300px;
      background: pink;
    }
  </style>
  <body>
    <div id="box" onclick="fun0()">
      <div id="box1" onclick="fun1()">
        <div id="box2" onclick="fun2()"></div>
      </div>
    </div>
  </body>
  <script>
    function fun0() {
      console.log('我是红色div')
    }
    function fun1() {
      event.stopPropagation()
      console.log('我是绿色div')
    }
    function fun2() {
      event.stopPropagation()
      console.log('我是粉色div')
    }
  </script>
</html>

 2.捕获事件

事件触发顺序是从外到内

 var box2 = document.getElementById('box2')
 //obj.addEventListener("事件名",函数名,事件流 true/false)
 //true:捕获,false:默认值代表冒泡
 box2.addEventListener('click', fun, true) 

//移除事件
box2.removeEventListener('click',fun,true)

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐