事件流

事件流描述的是从页面接收事件的顺序

事件流经历的三个阶段:

捕获阶段

当前目标阶段

冒泡阶段

用图示如下:

在这里插入图片描述

【注】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区域仍然会继续向上冒泡。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值