js阻止事件冒泡和捕获事件

 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)

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值