我們只點選了最裡面的那個div,但是在他的父級及以上div身上所繫結的事件都被觸發了,這顯
然不是我們想要的結果,我們實際需求是隻想要觸發點選的那個div上繫結的事件,我們該如何
阻止瀏覽器的這種事件處理機制呢?
<!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>
#info {
width: 500px;
height: 500px;
background: blue;
}
.box-1 {
width: 400px;
height: 400px;
background: red;
}
.box-2 {
width: 300px;
height: 300px;
background: yellow;
}
.box-3 {
width: 200px;
height: 200px;
background: orange;
}
.box-4 {
width: 100px;
height: 100px;
background: pink;
}
</style>
</head>
<body>
<div id="info">
<div class="box-1">
最外層
<div class="box-2">
第二層
<div class="box-3">
第三層
<div class="box-4">最底</div>
</div>
</div>
</div>
</div>
<script>
window.onload = function () {
let info = document.getElementById('info')
let box1 = document.querySelector('.box-1')
let box2 = document.querySelector('.box-2')
let box3 = document.querySelector('.box-3')
let bubbles = document.querySelector('.box-4')
bubbles.onclick = function (e) {
var ev = e || window.event;
if(ev && ev.stopPropagation) {
//非IE瀏覽器
ev.stopPropagation();
} else {
//IE瀏覽器(IE11以下)
ev.cancelBubble = true;
}
console.log("最底層盒子被點選了")
}
box3.onclick = function (e) {
var ev = e || window.event;
if(ev && ev.stopPropagation) {
//非IE瀏覽器
ev.stopPropagation();
} else {
//IE瀏覽器(IE11以下)
ev.cancelBubble = true;
}
console.log("第三個盒子被點選了")
}
box2.onclick = function (e) {
var ev = e || window.event;
if(ev && ev.stopPropagation) {
//非IE瀏覽器
ev.stopPropagation();
} else {
//IE瀏覽器(IE11以下)
ev.cancelBubble = true;
}
console.log("第二個盒子被點選了")
}
box1.onclick = function (e) {
var ev = e || window.event;
if(ev && ev.stopPropagation) {
//非IE瀏覽器
ev.stopPropagation();
} else {
//IE瀏覽器(IE11以下)
ev.cancelBubble = true;
}
console.log("第一個盒子被點選了")
}
}
//以上寫法就可以阻止事件的冒泡 每個盒子都只能列印一次
</script>
</body>
</html>
複製程式碼