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;
        }
    }

猜你喜欢

转载自www.cnblogs.com/YKingcc/p/9965283.html