jQuery中两种阻止事件冒泡的区别

方式一:event.stopPropagation();

方式二:return false;

但是这两种方式是有区别的。return false 不仅阻止了事件往上冒泡,而且阻止了事件本身。event.stopPropagation() 则只阻止事件往上冒泡,不阻止事件本身。

例子: 当文本输入框获取焦点后,在div1的mousedown事件中采用 event.stopPropagation(); 代码,我们鼠标单击红色区域后文本输入框光标失去。而当我们使用 return false; 代码时,鼠标单击红色区域光标仍然停留在文本输入框内。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="jquery-1.12.3.min.js"></script>
<script>
    $(document).ready(function(){
        $("#div1").mousedown(function(event){
            //event.stopPropagation();
            return false;
        });
        $("#div2").mousedown(function(event){
            alert("trigger mousedown event of rootDiv");
        });
    });
</script>
</head>
<body>
    <div id="rootDiv" style="position:relative;left:400px;top:200px;">
        <div>1.单击输入框,使输入框获取焦点:</div>
        <input id="input1" style="width:250px;" type="text"></input>
        <div id="div2">
            <div id="div1" style="width:200px;height:200px;"><br><br>2.然后再单击这里</div>
        </div>
    </div>
</body>
</html>

转载于:https://www.cnblogs.com/duanlianjiang/p/5532105.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值