js常用阻止冒泡事件

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

防止冒泡

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

stopPropagation也是事件对象(Event)的一个方法,作用是阻止目标元素的冒泡事件,但是会不阻止默认行为。什么是冒泡事件?如在一个按钮是绑定一个”click”事件,那么”click”事件会依次在它的父级元素中被触发 。stopPropagation就是阻止目标元素的事件冒泡到父级元素。如:·

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

上面的代码,Demo如下,我们单击test时,会依次触发alert(“li”),alert(“ul”),alert(“div”),这就是事件冒泡。

阻止冒泡

//code from http://caibaojian.com/javascript-stoppropagation-preventdefault.html
window.event? window.event.cancelBubble = true : e.stopPropagation();

 http://caibaojian.com/javascript-stoppropagation-preventdefault.html

    //得到事件
    function getEvent(){
        if(window.event)    {return window.event;}
        func=getEvent.caller;
        while(func!=null){
            var arg0=func.arguments[0];
            if(arg0){
                if((arg0.constructor==Event || arg0.constructor ==MouseEvent
                    || arg0.constructor==KeyboardEvent)
                    ||(typeof(arg0)=="object" && arg0.preventDefault
                    && arg0.stopPropagation)){
                    return arg0;
                }
            }
            func=func.caller;
        }
        return null;
    }
    //阻止冒泡
    function cancelBubble()
    {
        var e=getEvent();
        if(window.event){
            //e.returnValue=false;//阻止自身行为
            e.cancelBubble=true;//阻止冒泡
        }else if(e.preventDefault){
            //e.preventDefault();//阻止自身行为
            e.stopPropagation();//阻止冒泡
        }
    }

 


来源:前端开发博客