html中的标签都是相互嵌套的,我们可以将元素想象成一个盒子装一个盒子,document是最外面的大盒子。
当你单击一个div时,同时你也单击了div的父元素,甚至整个页面。那么是先执行父元素的单击事件,还是先执行div的单击事件 ???
比如:我们给页面中的一个div注册了单击事件,当你单击了div时,也就单击了body,单击了html,单击了document。
DOM 事件流会经历3个阶段:
-
捕获阶段
-
当前目标阶段
-
冒泡阶段
我们向水里面扔一块石头,首先它会有一个下降的过程,这个过程就可以理解为从最顶层向事件发生的最具体元素(目标点)的捕获过程;之后会产生泡泡,会在最低点( 最具体元素)之后漂浮到水面上,这个过程相当于事件冒泡。
<head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.box {
margin: 100px auto;
padding: 100px;
width: 400px;
height: 400px;
background-color: pink;
}
.son {
width: 200px;
height: 200px;
background-color: #bfa;
}
</style>
</head>
<body>
<div class="box">
<div class="son">son</div>
</div>
<script>
// 捕获阶段true 从外到内部的当前目标阶段
// 冒泡false/空 从当前目标阶段到外的document
var box = document.querySelector('.box');
var son = document.querySelector('.son');
// 捕获 从外到内的排序 先box 后 son (document -> son)
// son.addEventListener('click',function(){
// alert('捕获,son');
// },true);
// box.addEventListener('click',function(){
// alert('捕获,box');
// },true);
// 冒泡 从内到外的排序 先son 后 box (son -> document)
son.addEventListener('click',function(){
alert('冒泡 ,son');
},false);
box.addEventListener('click',function(){
alert('冒泡,box');
});
</script>
</body>
</html>