1. 程式人生 > >js--阻止冒泡,捕獲,預設行為

js--阻止冒泡,捕獲,預設行為

防止冒泡和捕獲

w3c的方法是e.stopPropagation(),IE則是使用e.cancelBubble = true·

var el = window.document.getElementById("a");
    el.onclick = function (e) {
        //如果提供了事件物件,則這是一個非IE瀏覽器
        if (e && e.stopPropagation) {
            //因此它支援W3C的stopPropagation()方法
            e.stopPropagation();
        }
        
else { //否則,我們需要使用IE的方式來取消事件冒泡 window.event.cancelBubble = true; return false; } }

 

取消預設事件

w3c的方法是e.preventDefault(),IE則是使用e.returnValue = false;·

var el = window.document.getElementById("a");
    el.onclick = function (e) {
        //如果提供了事件物件,則這是一個非IE瀏覽器
if (e && e.preventDefault) { //阻止預設瀏覽器動作(W3C) e.preventDefault(); } else { //IE中阻止函式器預設動作的方式 window.event.returnValue = false; return false; } }