js阻止事件传播/穿透(冒泡和捕获)

本文介绍了JavaScript中的事件传播,包括捕获事件(从顶层元素到目标元素)和冒泡事件(从目标元素到顶层元素)。讨论了W3C事件模型中的事件执行顺序,并详细讲解了addEventListener方法的第三个参数useCapture,用于控制事件是在捕获还是冒泡阶段触发。同时,提供了阻止冒泡和捕获事件的方法,帮助理解如何避免事件穿透。

阻止事件传播

阻止事件传播的代码在最下面

//代码1
//在下面的代码中,我需要添加一个全局事件,但是改全局事件不能包括imitationSelect,
imitationSelect.onclick= function(){
        if(selectUl.style.display=="block"){
            selectUl.style.display='none';
        }else{
            selectUl.style.display='block';
        };
        if(fa.className=="fa fa-caret-up"){
            fa.className='fa fa-caret-down';
        }else{
            fa.className='fa fa-caret-up';
        };
        // fa.className='fa fa-caret-up';
        if(window.event){          //if(window.event)即当触发事件时执行函数,单个对象时候可以不判断,但当对象多的时候可能会出bug
			//阻止事件传播,事件从点击的元素出发,向外(window)传播
            window.event.cancelBubble = true;
        }
    }

document.onclick=function(){ //全局(除了imitationSelect)绑定点击事件  
        fa.className='fa fa-caret-down'; //箭头样式
        selectUl.style.display='none';
        show(liArr);
    }

实现我们先来了解一下js的捕获和冒泡事件
以下为我的浅显理解(仅供参考
捕获事件
即从顶层元素向下直至目标元素,这个顶层元素包括document,甚至是window。
冒泡事件
即从目标元素向上直至顶层元素,顶层元素同上。
在这里插入图片描述
在w3c事件模型中

任何W3C事件模型中发生的事件都是先捕获,直到它到达目标元素,然后再向外冒泡。(即上图从右到左执行 顺序为: 3 2 1 2 3)
而我们所写的事件会在捕获过程或者冒泡过程中触发,而我们通常用addEventListener来绑定元素,但实际上addEventListener还有第3个参数,即控制事件是在冒泡过程还是捕获过程中触发。

这个参数名字为useCapture,类型为布尔值(true false),false为冒泡过程触发,true为捕获过程触发,默认为false。

值得一提的是onclick等绑定方法默认值也是在冒泡过程中触发的

//冒泡捕获具体的例子
//代码2
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>冒泡与捕获</title>
</head>
<style>
    div{
        width: 50px;
        height: 50px;
        background-color: yellow;
    }
    .father{
        width: 60px;
        height: 60px;
        background-color: red;
    }
    .grandpa{
        width: 70px;
        height: 70px;
        background-color: green;
    }
</style>
<body>
    <div class="grandpa">
        <div class="father">
            <div class="me">
                me
            </div>
        </div>
    </div>
</body>
    <script type="text/javascript">
        var me=document.getElementsByClassName('me')[0],
            father=document.getElementsByClassName('father')[0],
            grandpa=document.getElementsByClassName('grandpa')[0];
    
        
        me.addEventListener('click',()=>{
            console.log('me');
            alert('me');
        },true)
        father.addEventListener('click',()=>{
            console.log('father');
            alert('father');
        },true)
        grandpa.addEventListener('click',()=>{
            console.log('grandpa');
            alert('grandpa');
        },true)
        document.addEventListener('click',()=>{
            console.log('document');
            alert('document');
        },true)
        document.body.addEventListener('click',()=>{
            console.log('body');
            alert('body');
        },true)
        window.addEventListener('click',()=>{
            console.log('window');
            alert('window');
        },true)
    </script>
</html>

如代码2所示,useCapture为true时,输出顺序为:
在这里插入图片描述
useCapture为false或者不设置时:
在这里插入图片描述

//代码3
//捕获
        me.addEventListener('click',function(){
            console.log('me');
            alert('me');
            
        },true)
        father.addEventListener('click',function(){
            console.log('father');
            alert('father');
        },true)
        grandpa.addEventListener('click',function(){
            console.log('grandpa');
            alert('grandpa');
        },true)
        document.addEventListener('click',function(){
            console.log('document');
            alert('document');
        },true)
        document.body.addEventListener('click',function(){
            console.log('body');
            alert('body');
        },true)
        window.addEventListener('click',function(e){
            console.log('window');
            alert('window');
            // e.stopImmediatePropagation()
        },true)


       // 冒泡
        me.addEventListener('click',function(e){
            console.log('me');
            alert('me');
            // e.stopPropagation();
            // window.event.cancelBubble = true; 
        },false)
        father.addEventListener('click',function(){
            console.log('father');
            alert('father');
        },false)
        grandpa.addEventListener('click',function(){
            console.log('grandpa');
            alert('grandpa');
        },false)
        document.addEventListener('click',function(){
            console.log('document');
            alert('document');
        },false)
        document.body.addEventListener('click',function(){
            console.log('body');
            alert('body');
        },false)
        window.addEventListener('click',function(){
            console.log('window');
            alert('window');
        },false)

如代码3所示,即设置冒泡也设置捕获时:
其中me输出两次是因为me为根元素,无论useCapture为true还是false都会执行,所以输出两次。
在这里插入图片描述

禁止冒泡和捕获事件

阻止冒泡事件
如代码1中所示 window.event.cancelBubble = true;
考虑兼容:

if ( e && e.stopPropagation ) 
    //因此它支持W3C的stopPropagation()方法 
    e.stopPropagation();   //event.stopPropagation()
else 
    //否则,我们需要使用IE的方式来取消事件冒泡 
    window.event.cancelBubble = true; 
}

阻止捕获事件

e.stopImmediatePropagation()

相信现在再看代码1就能看懂如何阻止全局事件在imitationSelect里触发了

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值