js阻止冒泡;阻止JS事件穿透

本文探讨了JavaScript中如何阻止事件冒泡,展示了通过`event.stopPropagation()`和`event.cancelBubble=true`来防止事件穿透,从而确保事件在特定元素上停止传播的示例代码。
摘要由CSDN通过智能技术生成

js阻止冒泡;阻止JS事件穿透

js阻止冒泡

<html>
<title></title>
<head>
    <meta charset="utf-8">
    <style type="text/css">
        .divone{width:100px;height:100px;background:black;position: relative;cursor: pointer}
        .divchild{position: absolute;margin:10px;width:50px;height:50px;background:white;cursor: pointer}
    </style>
    <script type="text/javascript">
        function divone(){ 
            //这里是divone事件的代码 
            console.log('divone事件');
            stopPropagation();
        } 
        
        function divchild(){
            //这里是divchild事件的代码 
            console.log('divchild事件');
            stopPropagation();
        }

        function stopPropagation(e) {  
            e = e || window.event;  
            if(e.stopPropagation) { //W3C阻止冒泡方法  
                e.stopPropagation();  
            } else {  
                e.cancelBubble = true; //IE阻止冒泡方法  
            }  
        }
    </script>
</head>
<body>
    
    <div class="divone" onclick="divone(this)"> 
        
        <div class="divchild" onclick="divchild(this)"></div> 
        
    </div> 
 
</body>
</html>

阻止JS事件穿透

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值