事件捕获和事件冒泡
- 事件捕获:事件由父元素传递到子元素的过程
- 事件冒泡:事件由子元素传递到父元素的过程
- 应用:DOM对象.addEventListener(事件,事件处理程序,事件冒泡方式)
- 默认为false,为冒泡阶段完成事件处理
- true,为捕获阶段完成事件处理
- event.stopPropagation() 可以阻止事件流的进一步传播。
<head>
<style>
.father {
width: 400px;
height: 400px;
background-color: pink;
}
.son {
height: 200px;
width: 200px;
background-color: #ccc;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
let father = document.querySelector('.father')
let son = document.querySelector('.son')
// father.addEventListener('click', (e) => {
// console.log(111); // 111
// })
father.addEventListener('click', (e) => {
// 先执行父元素的点击事件,再执行子元素的点击事件
console.log(111); // 111 222
}, true)
son.addEventListener('click', (e) => {
console.log(222); // 222 111
// 阻止事件流传播
e.stopPropagation() // 222
})
</script>
拓展应用:事件代理(事件委托)
- 事件委托就是利用事件冒泡,只指定一个事件处理程序,就可以管理某一类型的所有事件
<style>
ul {
list-style: none;
}
li {
padding: 5px;
margin: 10px;
height: 30px;
width: 50px;
background-color: pink;
line-height: 30px;
text-align: center;
}
</style>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
let ul = document.querySelector('ul')
// 点击某个li 则那个li背景颜色改为红色
ul.addEventListener('click', (e) => {
e.target.style.backgroundColor = 'red'
})
</script>
</body>
`