冒泡和捕获,搞定它

直接上代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="five">555
    <div id="four">444
      <div id="three">333
        <div id="two">222
          <div id="one">111

          </div>
        </div>
      </div>
    </div>
  </div>
</body>
<script>
  document.getElementById('five').addEventListener('click', function(){
    alert('5')
  })
  document.getElementById('four').addEventListener('click', function(){
    alert('4')
  })
  document.getElementById('three').addEventListener('click', function(){
    alert('3')
  }, true)
  document.getElementById('two').addEventListener('click', function(){
    alert('2')
  })
  document.getElementById('one').addEventListener('click', function(){
    alert('1')
  })
</script>
</html>
<style>
  #five {
    width: 200px;
    height: 200px;
    border: 2px solid black;
  }
   #four {
    width: 150px;
    height: 150px;
    border: 2px solid black;    
  }
   #three {
    width: 100px;
    height: 100px;
    border: 2px solid black;
  }
   #two {
    width: 70px;
    height: 70px;
    border: 2px solid black;    
  }
   #one {
    width: 30px;
    height: 30px;
    border: 2px solid black;    
  }
</style>

第一,把第三个参数都设成false(即默认)

点击three, alert的结果是3 4 5,冒泡

点击two, alert的结果是 2 3 4 5,冒泡。顺序冒泡

第二,把第三个参数都设成true

点击three, alert的结果是5 4 3,捕获

点击two, alert的结果是 5 4 3 2,捕获。顺序捕获

第三,只把第三个参数设成true, 如代码所示

点击three, alert的结果是3 4 5

点击two, alert结果是3 2 4 5

点击two, alert结果是 3 1 2 4 5,这个最经典。试试咯

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值