高级前端dom【Q545】关于事件捕获和冒泡,以下代码输出多少

关于事件捕获和冒泡,以下代码输出多少

更多描述 代码见: 事件捕获和冒泡 - Codepen

以下代码输出多少:

<div class="container" id="container">
  <div class="item" id="item">
    <div class="btn" id="btn">Click me</div>
  </div>
</div>
document.addEventListener(
  "click",
  (e) => {
    console.log("Document click");
  },
  {
    capture: true,
  },
);
 
container.addEventListener(
  "click",
  (e) => {
    console.log("Container click");
    // e.stopPropagation()
  },
  {
    capture: true,
  },
);
 
item.addEventListener("click", () => {
  console.log("Item click");
});
 
btn.addEventListener("click", () => {
  console.log("Btn click");
});
 
btn.addEventListener(
  "click",
  () => {
    console.log("Btn click When Capture");
  },
  {
    capture: true,
  },
);

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 559

Author 回答者: shfshanyue

Document click
Container click
Btn click When Capture
Btn click
Item click

Author 回答者: ethanlamm

html

<div id="s1">
  s1
  <div id="s2">s2</div>
</div>

css

#s1 {
  width: 200px;
  height: 200px;
  background-color: burlywood;
  overflow: hidden;
}
#s2 {
  width: 100px;
  height: 100px;
  background-color: aquamarine;
  margin: 50px;
}

js

let s1 = document.getElementById("s1");
let s2 = document.getElementById("s2");
 
s2.onclick = function () {
  console.log("s2 click1");
};
s1.addEventListener(
  "click",
  function (e) {
    console.log("s1 冒泡事件");
  },
  false,
);
s2.addEventListener(
  "click",
  function (e) {
    console.log("s2 冒泡事件2");
  },
  false,
);
s2.addEventListener(
  "click",
  function (e) {
    console.log("s2 冒泡事件1");
  },
  false,
);
s1.addEventListener(
  "click",
  function (e) {
    console.log("s1 捕获事件");
  },
  true,
);
s2.addEventListener(
  "click",
  function (e) {
    console.log("s2 捕获事件");
  },
  true,
);
s2.onclick = function () {
  console.log("s2 click2");
};

结果输出

s1 捕获事件
s2 捕获事件
s2 click2
s2 冒泡事件2
s2 冒泡事件1
s1 冒泡事件

小结: 总顺序:捕获事件 ==> 冒泡事件(addEventListener) 或 on事件 冒泡事件addEventListener 和 on事件的执行顺序:按照定义时的顺序执行(书写代码的先后) 并且,冒泡事件addEventListener不会覆盖,有多少个事件就执行多少个,按顺序执行 而,相同的on事件会覆盖,后面的覆盖前面的