Skip to content
html
<!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>
  <style>
    .box {
      width: 200px;
      height: 200px;
      background: skyblue;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .outer {
      width: 150px;
      height: 150px;
      background: orange;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .inner {
      width: 50px;
      height: 50px;
      background: #bfa;
    }
  </style>
</head>
<body>
  <div class="box">
    <div class="outer">
      <div class="inner"></div>
    </div>
  </div>

  <ul id="ul">
    <li>2</li>
    <li>1</li>
    <span>3</span>
  </ul>

  <script>
    const box = document.querySelector('.box'),
          outer = document.querySelector('.outer'),
          inner = document.querySelector('.inner')

    
    inner.onclick = function (e) {
      // 阻止当前元素的事件冒泡行为, outer 和 box不会触发
      // e.stopPropagation
      //   ? e.stopPropagation() 
      //   : e.cancleBubble = true

      console.log('inner')

      // return 并不能阻止冒泡
      // return
    }

    outer.onclick = function (ev) {
      // 没有取消冒泡,点击 outer 时 box还会触发
      console.log('outer')
    }

    box.onclick = function (ev) {
      console.log('box')
    }

    // 事件委托
    // 原理:
    //   利用事件冒泡机制,当子元素被点击时会触发父元素事件的方法
    // 好处:
    //   提高性能,减少内存占用(事件监听回调从 n 变为 1)
    //   动态添加的内部元素也能响应

    // document.body.onclick = function (e) {
    //   const className = e.target.className

    //   if (className === 'inner') {
    //     console.log('inner')
    //   }
    //   else if (className === 'outer') {
    //     console.log('outer')
    //   }
    //   else if (className === 'box') {
    //     console.log('box')
    //   }
    // }

    // 一个页面,有若干个点击按钮,每个按钮有自己的click事件,给每一个访问用户添加一个
    // 属性,如果 banned = true,此用户点击网页上的任何按钮或元素,都不响应原来的事件,
    // 而是提示被封禁了。
    // window.addEventListener('click', (e) => {
    //   if (banner) {
    //     e.stopPropagation()
    //     alert('banned!')
    //   }
    // }, true)
  </script>
</body>
</html>