Appearance
html
<!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>
.box {
width: 200px;
height: 200px;
background: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
.outer {
width: 150px;
height: 150px;
background: orange;
display: flex;
justify-content: center;
align-items: center;
}
.inner {
width: 50px;
height: 50px;
background: #bfa;
}
</style>
</head>
<body>
<div class="div">
<div class="outer">
<div class="inner"></div>
</div>
</div>
<script>
let div = document.querySelector('.div'),
outer = document.querySelector('.outer'),
inner = document.querySelector('.inner')
// DOM0 事件绑定都是在冒泡阶段触发的
// DOM2 事件绑定可以控制在捕获还是冒泡阶段触发
inner.onclick = function (e) {
console.log('inner')
// e.path:冒泡的路径
// path: Array(7)
// 0: div.inner
// 1: div.outer
// 2: div.box
// 3: body
// 4: html
// 5: document
// 6: Window { ... }
}
outer.onclick = function () {
console.log('outer')
}
// 默认为false, 在冒泡阶段触发, 如果为true, 在捕获阶段触发。
div.addEventListener('click', () => {
console.log('box') // 最先输出, 因为在捕获阶段触发
}, true)
</script>
</body>
</html>