david2tdw/blog

[HTML] 事件冒泡与事件捕获

Opened this issue · 2 comments

[HTML] 事件冒泡与事件捕获
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #parent {
        width: 300px;
        height: 300px;
        background-color: yellow;
      }

      #child {
        margin: auto;
        width: 100px;
        height: 100px;
        background-color: gray;
      }

      body {
        border: 1px solid red;
      }
    </style>
  </head>

  <body>
    <div id="parent">
      parent
      <div id="child">child</div>
    </div>
  </body>
</html>

<script>
  
  var parent = document.getElementById('parent')
  var child = document.getElementById('child')

  // DOM0级
  // 冒泡阶段触发
  child.onclick = function () {
    console.log('child')
  }
  parent.onclick = function () {
    console.log('parent')
  }
  document.body.onclick = function () {
    console.log('body')
  }
  document.onclick = function () {
    console.log('document')
  }

  // DOM2级
  // false: 冒泡阶段触发
  // child.addEventListener(
  //   'click',
  //   function (e) {
  //     console.log('child')
  //   },
  //   false
  // )
  // parent.addEventListener(
  //   'click',
  //   function (e) {
  //     console.log('parent')
  //   },
  //   false
  // )
  // document.body.addEventListener(
  //   'click',
  //   function (e) {
  //     console.log('body')
  //   },
  //   false
  // )
  // document.addEventListener(
  //   'click',
  //   function (e) {
  //     console.log('document')
  //   },
  //   false
  // )

  // true 捕获阶段触发
  // child.addEventListener(
  //   'click',
  //   function (e) {
  //     console.log('child')
  //   },
  //   true
  // )
  // parent.addEventListener(
  //   'click',
  //   function (e) {
  //     console.log('parent')
  //   },
  //   true
  // )
  // document.body.addEventListener(
  //   'click',
  //   function (e) {
  //     console.log('body')
  //   },
  //   true
  // )
  // document.addEventListener(
  //   'click',
  //   function (e) {
  //     console.log('document')
  //   },
  //   true
  // )
</script>

target.addEventListener(type, listener, useCapture);

useCapture:

true: 捕获
false: 冒泡 (默认)

可以根据addEventListener()接收的第三个参数来规定是否选择事件冒泡或者事件捕获,true表示遵循事件捕获,false或者不传入参数表示遵循事件冒泡,建议使用事件冒泡,特殊情况下再使用事件捕获。

事件冒泡与事件捕获
EventTarget.addEventListener()