阻止冒泡的方法 event.stopPropagation();

标准浏览器 和  ie浏览器  
 w3c的方法是event.stopPropagation()       
 IE则是使用event.cancelBubble = true       bubble   冒泡  泡泡       cancel 取消 
 兼容的写法: 
 if(event && event.stopPropagation)
        {
             event.stopPropagation();  //  w3c 标准
        }
          else
          {

              event.cancelBubble = true;  // ie 678  ie浏览器8  

}

例子一

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button id="btn">按钮</button>
</body>
<script>

        var btn=document.getElementsByTagName("button")[0];
        document.οnclick=function(){
            alert("点击空白");
        }
    btn.οnclick=function(event){
        alert("点击button");
        //阻止冒泡
        event.stopPropagation();
    }
    window.οnclick=function(){
        alert("点击window");
    }


</script>
</html>

例子二
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        *{
            margin: 0px;
            padding: 0px;
            border: 0px;
        }
        #bg{
            width: 100%;
            height:100%;
            opacity: 0.5;
            background-color: #333;
            position: fixed;
            top:0;
            display: none;
        }
        #show{
            width: 300px;
            height: 300px;
            background-color: white;
            position: relative;
            top:20%;
            left: 40%;
            display: none;

        }

    </style>
</head>
<body>
<a href="#">登录</a>
<a href="#">注册</a>
<div id="bg"></div>
<div id="show"></div>
</body>
<script>
  var mya=document.getElementsByTagName("a")[0];
  var bg=document.getElementById("bg");
  var show=document.getElementById("show");
    mya.onclick = function(event){
        bg.style.display="block";
        show.style.display="block";
        event.stopPropagation();
    }
    document.οnclick=function(event){
      var target=event.target.id;
        alert(target);
        if(target!="show"){
            bg.style.display="none";
            show.style.display="none";
        }
    }
</script>
</html>

 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值