冒泡

事件触发顺序由内向外

// addEventListener 第三个参数为 useCapture
// false 为冒泡模式
id3.addEventListener('click', function(event){
    console.log('capture click id3', event)
}, false)

image.png

冒泡拦截

点击 id3 取消向外冒泡

// false 为冒泡模式
id3.addEventListener('click', function(event){
    event.cancelBubble = true
    // event.stopPropagation()
}, false)

image.png

捕获

事件触发顺序由外向内

image.png

// addEventListener 第三个参数为 useCapture
// true 为捕获模式
id3.addEventListener('click', function(event){
    console.log('capture click id3', event)
}, true)

完整代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
        #id1 {
            background: lightblue;
            padding: 50px;
        }
        #id2 {
            background: lightyellow;
            padding: 50px;
        }
        </style>
    </head>
    <body>
        <div id='id1'>
            id 1
            <div id="id2">
                id 2
                <button id='id3'>id3</button>
            </div>
        </div>
    </body>
    <script>
        // 事件冒泡
        var id1 = document.querySelector('#id1')
        var id2 = document.querySelector('#id2')
        var id3 = document.querySelector('#id3')
        id1.addEventListener('click', function(event){
            console.log('click id1', event)
        })
        id2.addEventListener('click', function(event){
            console.log('click id2', event)
        })
        id3.addEventListener('click', function(event){
            console.log('click id3', event)
            // event.cancelBubble = true
            event.stopPropagation()
        })

        // 事件捕获
        // id1.addEventListener('click', function(event){
        //     console.log('capture click id1', event)
        // }, true)
        // id2.addEventListener('click', function(event){
        //     console.log('capture click id2', event)
        // }, true)
        // id3.addEventListener('click', function(event){
        //     console.log('capture click id3', event)
        // }, true)
    </script>
</html>

TaoWu
15 声望2 粉丝