事件流描述的是从页面接收事件的顺序
事件流经历的三个阶段:
捕获阶段
当前目标阶段
冒泡阶段
用图示如下:
【注】JS代码中只能执行冒泡或者捕获其中一个阶段;
addEventListener(type,callback,useCaptrue),第三个参数是true即为捕获阶段,是false即为冒泡阶段,默认为false。
有些事件是没有冒泡的,onblur、onfocus、onmouseenter、onmouseleave
冒泡阶段
var son = document.querySelector('.son');
var father = document.querySelector('.father');
son.addEventListener('click',function(){
alert('son')
},false)
father.addEventListener('click',function(){
alert('father')
})
document.addEventListener('click',function(){
alert('document')
})
冒泡阶段从相对应的节点开始向上逐级传递至document。
捕获阶段
var son = document.querySelector('.son');
var father = document.querySelector('.father');
son.addEventListener('click',function(){
alert('son')
},true)
father.addEventListener('click',function(){
alert('father')
},true)
document.addEventListener('click',function(){
alert('document')
},true)
捕获阶段从最顶层节点开始向下传播到具体节点。
阻止事件冒泡
事件冒泡会带来好处但也会带来坏处,所以需要有一个方法来阻止它。
利用事件对象里面的stopPropagation()方法
e.stopPropagation()
<div class="father">
<div class="son">son盒子</div>
</div>
<script>
var son = document.querySelector('.son');
var father = document.querySelector('.father');
son.addEventListener('click',function(e){
e.stopPropagation()//阻止事件继续向上冒泡
alert('son')
},false)
father.addEventListener('click',function(){
alert('father')
})
document.addEventListener('click',function(){
alert('document')
})
</script>
此时,点击son区域,将不会再继续向上冒泡,但点击father区域仍然会继续向上冒泡。