一、冒泡
如图,点击div3(蓝色)时,三个div的事件都被触发了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件冒泡泡</title>
<style>
#div1{
width: 400px;
height: 400px;
background:#f00;
}
#div2{
width: 300px;
height: 300px;
background:#ff0;
}
#div3{
width: 200px;
height: 200px;
background:#0ff;
}
</style>
</head>
<body>
<div id="div1">
1111
<div id="div2">
2222
<div id="div3">3333</div>
</div>
</div>
<script>
var oDiv1 = document.getElementById("div1");
var oDiv2 = document.getElementById("div2");
var oDiv3 = document.getElementById("div3");
oDiv1.onclick = function(){
console.log("div1");
}
oDiv2.onclick = function(){
console.log("div2");
}
oDiv3.onclick = function(){
console.log("div3");
}
</script>
</body>
</html>
二、捕获
三、阻止事件冒泡
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件冒泡泡</title>
<style>
#div1{
width: 400px;
height: 400px;
background:#f00;
}
#div2{
width: 300px;
height: 300px;
background:#00ff00;
}
#div3{
width: 200px;
height: 200px;
background:#0ff;
}
</style>
</head>
<body>
<div id="div1">
1111
<div id="div2">
2222
<div id="div3">3333</div>
</div>
</div>
<script>
var oDiv1 = document.getElementById("div1");
var oDiv2 = document.getElementById("div2");
var oDiv3 = document.getElementById("div3");
oDiv1.onclick = function(e){
e = e || window.event;
e.stopPropagation();
e.cancleBubble = true;
console.log("div1");
}
oDiv2.onclick = function(e){
e = e || window.event;
e.stopPropagation();
e.cancleBubble = true;
console.log("div2");
}
oDiv3.onclick = function(e){
e = e || window.event;
e.stopPropagation();
e.cancleBubble = true;
console.log("div3");
}
</script>
</body>
</html>