阅读的文章是关于事件捕获与事件冒泡先后执行顺序 ,写得挺好的,就是我读的时候漏了一点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>DOM 冒泡</title>
<style type="text/css" media="all">
#parent {
height: 100px;
width: 100%;
background: green;
}
#child {
height: 50px;
width: 50%;
background: yellow;
}
#button {
height: 30px;
width: 10%;
background: white;
}
</style>
</head>
<body>
<div id="parent">
<div id="child">
<div id="button">按钮</div>
</div>
</div>
<script>
window.onload = function() {
const qId = (name) => document.getElementById(name);
const qTg = (name) => document.getElementsByTagName(name)[0];
const parent = qId('parent');
const child = qId('child');
const button = qId('button');
parent.addEventListener('click', () => console.log('parent click 事件'), true);
child.addEventListener('click', () => console.log('child click 事件'), true);
button.onclick = () => console.log('button click 冒泡');
button.addEventListener('click', () => console.log('button click 事件'), true);
parent.onclick = () => console.log('parent click 冒泡');
child.onclick = () => console.log('child click 冒泡');
}
</script>
</body>
</html>

首先结论是对的。

在捕获阶段,先由外向内执行捕获事件;

当事件触发在目标阶段时,会根据事件注册的先后顺序执行。也就是说如果该处既注册了冒泡事件,也注册了捕获事件,则按照注册顺序执行;

在冒泡阶段,由内向外冒泡到根节点上。

但我忘了 addEventListener 还有一个 useCapture 的参数。 useCapture 决定了添加的事件是冒泡还是捕获,而默认为 false ,所以是冒泡。 onclick 之类的都是冒泡。

阻止事件冒泡和事件捕获都使用 stopPropagation()preventDefault() 是用于取消事件,而不是阻止事件。