欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

addeventListener第三个参数

程序员文章站 2024-02-23 14:11:22
...
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>错误监控</title>
    <link rel="stylesheet" href="">
    <style>
        .child {
            background-color: pink;
            color: #ffffff;
            font-size: 42px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="father">
        <input class="child" type="text">hai zi </input>
    </div>
    <script type="text/javascript">
    
        const father = document.querySelector('.father')
        const child = document.querySelector('.child')

        
        father.addEventListener('click', function (event) {
            console.log('father');
            // 阻止捕获
            event.stopImmediatePropagation()
        }, true)
        child.addEventListener('click', function (event) {
            console.log('child');
            // 阻止冒泡
            event.stopPropagation()
        }, false)
    </script>
</body>
</html>

要看详细的介绍,最好去看MDN文档。这里只是介绍第三个参数为true或者false的对应的情况

true: 意味着事件从捕获到冒泡
false: 意味着事件从冒泡到捕获
并不是自己一直以为的是阻止冒泡

相关标签: js