什么是事件冒泡?
多个元素嵌套且元素之间有层次关系,并且这些元素都注册了相同的事件。如果最里面的元素的事件被触发,那么外面的元素的事件也自动跟着触发。
例:
<!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>