JS日记之DOM事件流

在这里插入图片描述
在这里插入图片描述
光说不练假把式上demo!
代码:

<!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.0">
    <title>Document</title>
    <style type="text/css">
    .father{
        width: 500px;
        height: 500px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: aqua;
    }
    .son{
        width: 200px;
        height: 200px;
        background-color: yellow;
    }
    
    </style>
</head>
<body>
    <div class="father">father
    <div class="son">son</div>
    </div>
    <script>
        var father=document.querySelector('.father')
        var son=document.querySelector('.son')
        /* addEventListener第三个参数为ture则为捕获 */
        father.addEventListener('click',function(){
            alert('father')
        },true)
        son.addEventListener('click',function(){
            alert('son')
        },true)
        /* addEventListener第三个参数为false或省略则为冒泡 */
        /* father.addEventListener('click',function(){
            alert('father')
        },true)
        son.addEventListener('click',function(){
            alert('son')
        },true) */
    </script>
</body>
</html>

完整代码打开即可验证!

注意及解释:
1.捕获和冒泡的顺序:
在这里插入图片描述
这个顺序很重要!

2.传递的是一个被激活的事件,但是事件函数要看接收方,下面进行验证。
代码:

<div id="father">father
    <div id="son">son</div>
</div>    
    <script>
        var father=document.querySelector('#father')
        var son=document.querySelector('#son')
        father.addEventListener('click',function(){
            alert('father')
        },true)
        son.addEventListener('click',function(){
            alert('son')
        },true)
    </script>

上面代码为捕获。我们点击son发现进行了两词弹出对话框,内容分别为father和son。如果去掉alert(‘son’),会发现只弹出father。


参考文章:
浅谈事件冒泡和事件捕获

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值