JavaScript事件的捕获和冒泡过程

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Example</title>
</head>

<body>
    <input type="button" value="click" id="test">
    <script>
        // 如果是在捕获阶 段调用的事件处理程序,那么 eventPhase 等于 1
        // 如果事件处理程序处于目标对象上,则 event- Phase 等于 2;
        // 如果是在冒泡阶段调用的事件处理程序,eventPhase 等于 3
        var btn = document.getElementById('test')

        btn.onclick = function(e) {
            console.log(e.eventPhase)
        }

        document.body.addEventListener('click',function(e){
            console.log('捕获',e.eventPhase)
        },true) //第三个参数设置为true,意为在捕获阶段

        document.body.onclick = function(e) {
            console.log('冒泡',e.eventPhase)
        }
    </script>
</body>

</html>

运行结果图:


猜你喜欢

转载自blog.csdn.net/m0_37897013/article/details/80294780