JS target bubbling capture

Target : The target here is the event source. When propagating, it will propagate from the target to the parent, body, html, document, window

The default propagation method of window is bubbling

Bubbling: When the event propagates, it propagates from the target to the parent, body...window

Capture: starting from the top layer, passing down layer by layer until reaching the target, it will not pass down again

bubble

    <style>
        #box1 {
      
      
            width: 500px;
            height: 500px;
            background-color: pink;
        }

        #box2 {
      
      
            width: 200px;
            height: 200px;
            background-color: green;
        }
    </style>


     <div id="box1">
        <div id="box2"></div>
    </div>
    <script>
        var box1 = document.getElementById('box1')
        var box2 = document.getElementById('box2')
        var myBody = document.body

        box1.onclick = function (e) {
      
      
            console.log('触发了 box1 的点击事件')
        }
        *点击box1,打印结果为:触发box1和触发body
        
        box2.onclick = function () {
      
      
            console.log('触发了 box2 的点击事件')
        }
        *点击box2,打印结果为:触发box2,触发box1,触发body
        
        myBody.onclick = function () {
      
      
            console.log('触发了 body 的点击事件')
        }
        *点击body ,打印结果为:触发body
    </script>

capture

    <style>
        #box1 {
      
      
            width: 500px;
            height: 500px;
            background-color: pink;
        }

        #box2 {
      
      
            width: 200px;
            height: 200px;
            background-color: green;
        }
    </style>


     <div id="box1">
        <div id="box2"></div>
    </div>
    <script>
        var box1 = document.getElementById('box1')
        var box2 = document.getElementById('box2')
        var myBody = document.body

       *  捕获,需要传递第三个参数为true
       *  addEventListener 第三个参数默认值为 false 代表传播方式为冒泡
       *  如果想改变传播方式为捕获, 那么需要将第三个参数传递为true
       
        box1.addEventListener('click', function () {
      
      
            console.log('触发了 box1 的点击事件')
        }, true)
        *点击box1,打印结果为:触发body和触发box1
        
        box2.addEventListener('click', function () {
      
      
            console.log('触发了 box2222 的点击事件')
        }, true)
        *点击box2,打印结果为:触发body,触发box1,触发box2
        
        myBody.addEventListener('click', function () {
      
      
            console.log('触发了 body 的点击事件')
        }, true)
        *点击body ,打印结果为:触发body
    </script>

Guess you like

Origin blog.csdn.net/weixin_48649246/article/details/127700667