js阻止冒泡事件和默认事件的方法兼容性写法

HTML代码:

<div id="swap">
    <div id="box">
        <a href="http://www.baidu.com" id="btn">点我</a>
    </div>
</div> 

js代码:

 var swap=document.getElementById("swap");
 var box=document.getElementById("box");
 var btn=document.getElementById("btn");
swap.onclick=function(){
    alert("我是swap");
};
box.onclick=function(){
    alert("我是box");
}

1.阻止冒泡事件方法  event.stopPropagation();

btn.onclick=function(e){
    var event=window.event||e;
    alert("我是btn");
    window.event?event.cancelBubble=true:event.stopPropagation();
}

这样只阻止了冒泡事件并未阻止a标签跳转到百度页面的默认事件;弹出“我是btn”点击确定后跳转到百度页面

2. 阻止默认事件方法 event.preventDefault();

btn.onclick=function(e){
    var event=window.event||e;
    alert("我是btn");
    event.preventDefault();
}

阻止了a标签跳转百度的默认事件,依次弹出“我是btn”“我是box”“我是swap”而不会调到百度页面

3.阻止冒泡和默认事件  event.stopPropagation();    return false;

btn.onclick=function(e){
    var event=window.event||e;
    alert("我是btn");
    window.event?event.cancelBubble=true:event.stopPropagation();
    return false;
}

既阻止了冒泡事件也阻止了默认事件,只弹出“我是btn”;

个人总结,希望能帮到你




猜你喜欢

转载自blog.csdn.net/mayue24/article/details/80847816