防止冒泡和捕獲
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