事件冒泡和事件捕获(原生)

167 阅读1分钟

事件冒泡 儿子---->父亲

    <div id="first">
        <div id="second" >
            <div id="third" >
                <button id="button">事件冒泡</button>
            </div>
        </div>
    </div>
<script>

        document.getElementById("button").addEventListener("click",function(){
            alert("button");
        },false);

        document.getElementById("third").addEventListener("click",function(){
            alert("third");
        },false);

        document.getElementById("second").addEventListener("click",function(){
            alert("second");
        },false);        

        document.getElementById("first").addEventListener("click",function(){
            alert("first");
        },false);

    </script>
这时,我们只点击button元素,会依次触发button third second filst事件,就是儿子->父亲的顺序。
但是如果我们不希望事件冒泡呢?那么如何阻止事件冒泡?
实际上,事件的对象有一个stopPropagation()方法可以阻止事件冒泡##### ,我们只需要把上个例子中button的事件处理程序修改如下:
document.getElementById("button").addEventListener("click",function(event){
            alert("button");
            event.stopPropagation();    
        },false);

事件捕获 父亲---->儿子

跟上面相反 阻止方法 event.stopImmediatePropagation();