事件捕获和事件冒泡

<body>
    <div id="first" style=" 300px;height: 300px;background-color: #ccc;">1
        <div id="second" style=" 200px;height: 200px;background-color: #f0f;">2
            <div id="third" style=" 100px;height: 100px;background-color: #999;">3
                <button id="btn">按钮</button>
            </div>
        </div>
    </div>
    <script src="./jquery.min.js"></script>
    <script>
        var $btn = $('#btn')
        var $first = $('#first')
        var $second = $('#second')
        var $third = $('#third')

        // 通过传入最后一个参数的不同来确定执行捕获还是冒泡,false是绑定的冒泡,true是绑定的捕获
        
        $btn[0].addEventListener("click", function(e){
            console.log(3);
        }, true);

        $btn[0].addEventListener("click", function(e){
            console.log(4);
        }, false);
        // 事件源本身的捕获还是冒泡的顺序是按书写的顺序来的,没有先后之分
        
        $third[0].addEventListener("click", function(e){
            console.log(5);
        }, false);
        $second[0].addEventListener("click", function(e){
            console.log(6);
        }, false);


        $third[0].addEventListener("click", function(e){
            console.log(2);
        }, true);
        $second[0].addEventListener("click", function(e){
            console.log(1);
        }, true);
    </script>
</body>

上边的打印结果是依次从1到6,执行的顺序是先执行捕获过程,再执行冒泡过程,捕获是在window开始一直到事件源,冒泡是从事件源开始到window,事件源的捕获和冒泡没有先后顺序之分,只是哪个先绑定哪个先执行

event.stopPropagation()起到阻止捕获和冒泡阶段中当前事件的进一步传播

原文地址:https://www.cnblogs.com/wyongz/p/13611849.html