結構
<style>
.father {
width: 500px;
height: 500px;
background: black;
}
.son {
width: 250px;
height: 250px;
background: yellow;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
效果

一、事件冒泡
<script>
let father = document.querySelector('.father')
let son = document.querySelector('.son')
father.addEventListener('click',()=>{
console.log('father');
})
son.addEventListener('click',(e)=>{
console.log('son');
})
</script>
父盒子和子盒子是嵌套關系 當點擊子盒子和父盒子共同的部分時,就會產生一種現象 叫作事件冒泡,分別給父子盒子注冊事件后 列印輸出結果

發現點擊子盒子時 父盒子的事件也觸發了,為什么叫冒泡呢 因為子盒子在父盒子里面 是從里向外 冒出來的,所以稱為冒泡,
阻止冒泡
通過事件引數e.stopPropagation方法達到阻止冒泡的效果
son.addEventListener('click',(e)=>{
e.stopPropagation()
console.log('son');
})
如果是vue
<button @click.stop="hClick"></button>
二、事件捕獲
事件捕獲 只能通過addEventListener 的第三個引數去實作,如果不寫則為false,如果為ture則是開啟了事件捕獲, 通過下面的代碼繼續點擊相同的部分,
let father = document.querySelector('.father')
let son = document.querySelector('.son')
father.addEventListener('click',()=>{
console.log('father');
},true)
son.addEventListener('click',(e)=>{
console.log('son');
})

捕獲正好和冒泡相反,是從外向里傳遞事件,注意onclick并不能達到事件捕獲的效果 ,只有addEventListener 的第三個引數手動去實作,
三、事件委托
事件委托本質上發生在事件中,委托事情交給被人去做,達到自己做的一個目的,如果一個元素是動態創建的且要給該元素注冊事件,那么必須使用委托,給ul注冊點擊事件 e.target拿到的是 每個li
<body>
<ul>
<li>第1個li</li>
<li>第2個li</li>
<li>第3個li</li>
<li>第4個li</li>
</ul>
<script>
// 事件捕獲
let ul = document.querySelector('ul');
ul.addEventListener('click', function (e) {
console.log(e.target.innerText);
})
</script>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/293199.html
標籤:其他
上一篇:淺學JavaScript04
