JavaScript中事件冒泡

本文详细介绍了事件冒泡的概念,即在一个嵌套元素结构中,内部元素触发事件时,外部元素也会相继触发相同事件。并通过实例展示了如何使用stopPropagation()和cancelBubble属性来阻止事件冒泡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是事件冒泡?

多个元素嵌套且元素之间有层次关系,并且这些元素都注册了相同的事件。如果最里面的元素的事件被触发,那么外面的元素的事件也自动跟着触发。

例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #div1{
            width: 300px;
            height: 200px;
            background: red;

        }
        #div2{
            width: 250px;
            height: 150px;
            background: green;
        }
        #div3{
            width: 200px;
            height: 100px;
            background: yellow;
        }
    </style>
</head>
<body>
    <div id="div1">
        <div id="div2">
            <div id="div3"></div>
        </div> 
    </div>
<script>
    //为三个div注册同一个事件,点击div显示div的ID名。
    document.getElementById("div1").onclick =function(){
        console.log(this.id);
    };
    document.getElementById("div2").onclick =function(){
        console.log(this.id);
    };
    document.getElementById("div3").onclick =function(){
        console.log(this.id);
    }
</script>
</body>
</html>

点击DIV1
在这里插入图片描述
点击DIV2
在这里插入图片描述
点击DIV3
在这里插入图片描述
如上图所示,三个DIV元素注册了同一个点击事件并输出DIV的id。当点击最里层的DIV时,外面的DIV注册的事件也随之自动触发。

如何阻止事件冒泡

方法一

<script>
    //为三个div注册同一个事件,点击div显示div的ID名。
    document.getElementById("div1").onclick =function(){
        console.log(this.id);
    };
    document.getElementById("div2").onclick =function(){
        console.log(this.id);
    };
    document.getElementById("div3").onclick =function(e){
        console.log(this.id);
        //阻止事件冒泡
        e.stopPropagation(); //谷歌,火狐支持。IE8不支持
    }
</script>

方法二

<script>
    //为三个div注册同一个事件,点击div显示div的ID名。
    document.getElementById("div1").onclick =function(){
        console.log(this.id);
    };
    document.getElementById("div2").onclick =function(){
        console.log(this.id);
    };
    document.getElementById("div3").onclick =function(){
        console.log(this.id);
        //阻止事件冒泡
         window.event.cancelBubble =true;//谷歌,IE8浏览器。火狐浏览器不支持
    }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值