事件流指的是页面中接收事件的顺序。
事件发生时,会在元素节点间按照规定顺序传播。
事件流分为三阶段:
- 捕获阶段 从document -> html -> body -> 父元素 -> 子元素,由外向内传播。
- 当前目标阶段
- 冒泡阶段 从当前目标 由内向外传播。
<style>
.father {
overflow: hidden;
width: 300px;
height: 300px;
margin: 100px auto;
background-color: pink;
text-align: center;
}
.son {
width: 200px;
height: 200px;
margin: 50px;
background-color: purple;
line-height: 200px;
color: #fff;
}
</style>
<div class="father">
<div class="son">son儿子</div>
</div>
<script>
var father = document.querySelector('.father');
var son = document.querySelector('.son');
function sonf(e) {
console.log('son');
}
function fatherf(e) {
console.log('father');
}
//传统方式 默认冒泡执行 son father
son.onclick = sonf;
father.onclick = fatherf;
//监听器方式 默认冒泡执行 son father
son.addEventListener('click',sonf);
father.addEventListener('click',fatherf);
//监听器方式 false冒泡执行 son father
son.addEventListener('click',sonf,false);
father.addEventListener('click',fatherf,false);
//监听器方式 true捕捉执行 father son
son.addEventListener('click',sonf,true);
father.addEventListener('click',fatherf,true);
</script>