事件 捕获和冒泡(应用场景:事件委托)

1,642 阅读1分钟

捕获:自顶而下,window -> 目标元素 冒泡:自底向上,目标元素 -> window

  • window.addEventListener 监听的是什么阶段的事件?

冒泡阶段

window.addEventListener('click',()=>{
  
})//默认这里第三个参数是false

捕获阶段

window.addEventListener('click',()=>{

},true)

案例

  • 在历史界面上,添加一个属性,banner = true, 不再响应原理的函数,提示alter 解决方法:在最顶层绑定一个捕获事件,去拦截冒泡,
window.addEventListener('click',()=>{
  if(banned){
    e.stopPropagation()//阻止捕获
  }
},true)

应用场景:事件委托

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
</head>
<body>
<ul id="ul">
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
</ul>
</body>
<script type="text/javascript">

 const ul = document.querySelector('ul')
  ul.addEventListener('click',function (e) {
    const target = e.target
    if (target.tagName.toLowerCase() === 'li') {
      const liList = this.querySelectorAll('li')
      const index = Array.prototype.indexOf.call(liList,target)
      alert(`内容是${target.innerHTML},索引${index}`)
    }
  })

</script>
</html>