事件捕获 -- 点击底层容器,事件从表层向底层触发
<div id="top">表层
<div id="bottom" style="margin: 10px;border: 1px solid red;">底层</div>
</div>
<script>
const surface = document.getElementById('top')
const bottom = document.getElementById('bottom')
surface.addEventListener('click',()=>{
alert('表层')
},true)
bottom.addEventListener('click',() => {
alert('底层')
},true)
</script>
事件冒泡 -- 底层
和表层都进行了事件绑定,当点击底层容器,事件由底层向顶层依次被触发
影响:当想要只触发底层容器的绑定事件时,事件冒泡就会干扰我们的操作
阻止冒泡 --stopPropagation()
const surface = document.getElementById('top')
const bottom = document.getElementById('bottom')
surface.addEventListener('click',()=>{
alert('表层')
})
bottom.addEventListener('click',(e)=>{
console.log('底层');
//阻止事件冒泡
//e.stopPropagation()
})