DOM事件流——事件传播过程(JS事件冒泡)
事件分为捕获阶段、目标阶段、冒泡阶段
注意:
- JS代码只能执行捕获其中的一个阶段;
- onclick和attachEvent只能得到冒泡;
- addEventListener第三个参数中
true -> 捕获阶段
false -> 冒泡阶段
代码演示
盒子嵌套情况:
<div class="father">
<div class="son">son盒子</div>
</div>
(1)设置捕获捕获阶段
var son = document.querySelector('.son');
son.addEventListener('click', function() {
alert('son');
}, true);
var father = document.querySelector('.father');
father.addEventListener('click', function() {
alert('father');
}, true);
此时先弹出father,后弹出son
(2)设置捕获捕获阶段
var son = document.querySelector('.son');
son.addEventListener('click', function() {
alert('son');
}, false);
var father = document.querySelector('.father');
father.addEventListener('click', function() {
alert('father');
}, false);
document.addEventListener('click', function() {
alert('document');
})
此时先弹出son,后弹出father
(3)另:
阻止事件冒泡
var son = document.querySelector('.son');
son.addEventListener('click', function(e) {
alert('son');
e.stopPropagation(); // 阻止事件冒泡
}, false);
var father = document.querySelector('.father');
father.addEventListener('click', function() {
alert('father');
}, false);
document.addEventListener('click', function() {
alert('document');
})
此时事件只弹出son