js阻止事件冒泡和默认事件(右键点击)

话不多说,上代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            padding:0;
            margin:0;
        }
        li{
            width:50px;
            height:20px;
            border:1px solid red;
            background-color: antiquewhite;
            text-align: center;
            list-style: none;
            cursor: pointer;
        }
        .preDefault{
            background-color: yellow;
            width:500px;
            height:500px;
            margin:auto;
        }
    </style>
</head>
<body>
    <div onclick="alert('点击了div')">
        <ul onclick="alert('点击了ul')">
            <li>
                test
            </li>
        </ul>
    </div>
    <div class="preDefault">
        
    </div>
</body>
<script>
    // 阻止事件冒泡
    const li = document.querySelector("li")
    li.onclick =  function(e){
        if(e.stopPropagation){
            e.stopPropagation()
        }else{
            window.event.cancel = true//兼容IE6、7、8
        }
        alert("点击了li")
    }

    // 阻止默认事件
    const preDefault = document.querySelector(".preDefault")
    preDefault.oncontextmenu =function(e){//鼠标右键点击
        if(e.preventDefault){
            e.preventDefault()
        }else{
            window.event.returnValue = false //兼容IE6、7、8
        }
        alert("阻止了默认事件")
    }
</script>
</html>

阻止事件冒泡:

e.stopPropagation() //w3c写法
window.event.cancel = true //低版本ie写法
//兼容写法如下:
if(e.stopPropagation){
   e.stopPropagation()
}else{
   window.event.cancel = true//兼容IE6、7、8
}

阻止默认事件(比如:右键点击事件)

e.preventDafault()//w3c写法
window.event.returnValue = false //兼容低版本ie
//兼容性写法如下:
if(e.preventDefault){
    e.preventDefault()
}else{
    window.event.returnValue = false //兼容IE6、7、8
}

如果对您有一丝的帮助,请赏个赞可好~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值