事件冒泡与事件捕获

事件冒泡

        事件冒泡是自下而上的去触发事件

例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件冒泡</title>
</head>
<body>
<div id="parent">
      <div id="child" class="child">事件冒泡</div>
</div>
</body>
<script>
    document.getElementById("parent").addEventListener("click",function(e)   {
        console.log("parent事件被触发,"+this.id);
    })

    document.getElementById("child").addEventListener("click",function(e)
    {
        console.log("child事件被触发,"+this.id)
    })
</script>
</html>

结果图:

结论:

    先child,然后parent。事件的触发顺序自内向外,这就是事件冒泡。

事件捕获

        事件捕获指的是从document到触发事件的那个节点,即自上而下的去触发事件

例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件捕获</title>
</head>
<body>
<div id="parent">  
    <div id="child" class="child">事件捕获</div>
</div>
</body>
<script>
    document.getElementById("parent").addEventListener("click", function (e) {
        console.log("parent事件被触发");
    }, true)
    document.getElementById("child").addEventListener("click", function (e) {
        console.log("child事件被触发")
    }, true)

</script>
</html>

结果图:

扫描二维码关注公众号,回复: 2434929 查看本文章

结论:

    先parent,然后child。事件触发顺序变更为自外向内,这就是事件捕获。

猜你喜欢

转载自blog.csdn.net/qq_34607371/article/details/81208123