js冒泡和捕獲是事件的兩種行為爽雄,使用event.stopPropagation()起到阻止捕獲和冒泡階段中當(dāng)前事件的進一步傳播斋日。使用event.preventDefault()可以取消默認(rèn)事件封豪。
1. 阻止冒泡
function stopBubble(e) {
//如果提供了事件對象角虫,則這是一個非IE瀏覽器
if ( e && e.stopPropagation )
//因此它支持W3C的stopPropagation()方法
e.stopPropagation();
else
//否則末购,我們需要使用IE的方式來取消事件冒泡
window.event.cancelBubble = true;
}
2. 阻止默認(rèn)行為
//阻止瀏覽器的默認(rèn)行為
function stopDefault( e ) {
//阻止默認(rèn)瀏覽器動作(W3C)
if ( e && e.preventDefault )
e.preventDefault();
//IE中阻止函數(shù)器默認(rèn)動作的方式
else
window.event.returnValue = false;
return false;
}
事件注意點
- event代表事件的狀態(tài)熙揍,例如觸發(fā)event對象的元素、鼠標(biāo)的位置及狀態(tài)盖灸、按下的鍵等等蚁鳖;
- event對象只在事件發(fā)生的過程中才有效。
firefox里的event跟IE里的不同赁炎,IE里的是全局變量醉箕,隨時可用;firefox里的要用參數(shù)引導(dǎo)才能用徙垫,是運行時的臨時變量讥裤。
在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
}