事件流的2个阶段

发布时间 2023-08-17 18:04:11作者: 弩哥++

image

第一个阶段:由父到子(捕获)

第二个阶段:由子到父(冒泡)

绑定事件/注册事件

  • 事件源.addEventListener(事件类型,事件函数,是否使用捕获)
  • 其中第三个参数默认为false,不使用捕获,实际工作也多使用冒泡,如事件委托
  • L0的事件是没有捕获阶段的,如事件源.onclick=事件函数
  • 如果要使用捕获,就需要更改第三个参数为true

事件捕获示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <style>
        .box {
            width: 500px;
            height: 500px;
            background-color: coral;
        }

        .box1 {
            width: 400px;
            height: 400px;
            background-color: skyblue;
        }

        .box2 {
            width: 300px;
            height: 300px;
            background-color: rebeccapurple;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="box1">
            <div class="box2"></div>
        </div>
    </div>

    <script>
        const box = document.querySelector('.box')
        const box1 = document.querySelector('.box1')
        const box2 = document.querySelector('.box2')
        box.addEventListener('click', function () {
            console.log('我点击了box')

        },true)
        box1.addEventListener('click', function () {
            console.log('我点击了box1')

        },true)
        box2.addEventListener('click', function () {
            console.log('我点击了box2')

        },true)

    </script>
</body>

</html>

image

事件冒泡示例

  • 简单理解:当一个元素触发事件后,会依次向上调用所有父级元素的 同名事件

取消掉第三个参数,因为默认的就是false

image

阻止冒泡

  • 因为默认就有冒泡模式的存在,所以容易导致事件影响到父级元素
  • 阻止事件冒泡需要拿到事件对象
  • e.stopPropagation()