js阻止冒泡和取消事件

防止冒泡和捕获

w3c 方法:e.stopPropagation()

IE方法:e.cancelBubble = true

html:

<div onclick='alert("div出发");'>
    <ul onclick='alert("ul触发");'>
        <li id="li">test</li>
    </ul>
</div>        

js:

var li = document.getElementById('li');
li.onclick = function(e) {
    window.event ? window.event.cancelBubble = true : e.stopPropagation();
    alert("li触发");
}

取消默认事件

w3c方法:e.preventDefault()

IE方法:e.returnValue = false

// //假定有链接<a href="http://baidu.com/" id="testA" >caibaojian.com</a>
var a = document.getElementById("testA");
a.onclick = function(e) {
    if(e.preventDefault) {
        e.preventDefault();
    } else {
        window.event.returnValue == false;
    }
    console.log('点击了a')
}

return false

javascript的return false只会阻止默认行为,而是用jQuery的话则既阻止默认行为又防止对象冒泡。

//原生js,只会阻止默认行为,不会停止冒泡
<div id='div'  onclick='alert("div");'>
<ul  onclick='alert("ul");'>
<li id='ul-a' onclick='alert("li");'><a href="http://caibaojian.com/"id="testB">caibaojian.com</a></li>
</ul>
</div>
var a = document.getElementById("testB");
a.onclick = function(){
return false;
};
//使用jQuery,既阻止默认行为又停止冒泡
<div id='div'  onclick='alert("div");'>
<ul  onclick='alert("ul");'>
<li id='ul-a' onclick='alert("li");'><a href="http://caibaojian.com/"id="testC">caibaojian.com</a></li>
</ul>
</div>
$("#testC").on('click',function(){
return false;
});

总结使用方法

阻止冒泡

function stopBubble(e) { 
//如果提供了事件对象,则这是一个非IE浏览器 
if ( e && e.stopPropagation ) 
    //因此它支持W3C的stopPropagation()方法 
    e.stopPropagation(); 
else 
    //否则,我们需要使用IE的方式来取消事件冒泡 
    window.event.cancelBubble = true; 
}

阻止默认行为

//阻止浏览器的默认行为 
function stopDefault( e ) { 
    //阻止默认浏览器动作(W3C) 
    if ( e && e.preventDefault ) 
        e.preventDefault(); 
    //IE中阻止函数器默认动作的方式 
    else 
        window.event.returnValue = false; 
    return false; 
}

事件注意点
event代表事件的状态,例如触发event对象的元素、鼠标的位置及状态、按下的键等等;
event对象只在事件发生的过程中才有效。
firefox里的event跟IE里的不同,IE里的是全局变量,随时可用;firefox里的要用参数引导才能用,是运行时的临时变量。
在IE/Opera中是window.event,在Firefox中是event;而事件的对象,在IE中是window.event.srcElement,在Firefox中是event.target,Opera中两者都可用。

下面两句效果相同:

function a(e){
var e = (e) ? e : ((window.event) ? window.event : null); 
var e = e || window.event; // firefox下window.event为null, IE下event为null
}

原链接:http://caibaojian.com/javascript-stoppropagation-preventdefault.html

猜你喜欢

转载自www.cnblogs.com/suitongyu/p/12677937.html