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

来源:互联网 发布:115浏览器for mac 编辑:程序博客网 时间:2024/05/20 14:18
标准浏览器 和  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.onclick=function(){            alert("点击空白");        }    btn.onclick=function(event){        alert("点击button");        //阻止冒泡        event.stopPropagation();    }    window.onclick=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.onclick=function(event){      var target=event.target.id;        alert(target);        if(target!="show"){            bg.style.display="none";            show.style.display="none";        }    }</script></html>

 }

0 0