概述
瀏覽器事件傳播存在三個(gè)階段:捕獲階段,目標(biāo)階段奴愉,冒泡階段
- 捕獲階段:從window對(duì)象派發(fā)到事件目標(biāo)的父級(jí)的過(guò)程
- 目標(biāo)階段:目標(biāo)被找到
- 冒泡階段:從目標(biāo)父級(jí)到window對(duì)象
在任何階段調(diào)用 stopPropagation 都將終止本次事件的傳播琅摩。
查看e.path可以查看dom鏈路
事件傳播
代碼實(shí)驗(yàn)
dom以及style如下
<style>
#root{
width: 100px;
height: 100px;
background: red;
}
#parent{
width: 60px;
height: 60px;
background: yellow;
}
#child{
width: 30px;
height: 30px;
background: blue;
}
</style>
<div id="root">
<div id="parent">
<div id="child"></div>
</div>
</div>
三層嵌套.png
如上所述,我們嵌套了三層結(jié)構(gòu)躁劣,root迫吐,parent,child账忘,下面我們給每一層綁定捕獲和冒泡的點(diǎn)擊事件
var getDom = function(id){
return document.getElementById(id)
}
var root = getDom('root')
var parent = getDom('parent')
var child = getDom('child')
root.addEventListener('click', function(e){
console.log('root---捕獲階段')
}, true)
parent.addEventListener('click', function(e){
console.log('parent---捕獲階段')
}, true)
child.addEventListener('click', function(e){
console.log('child---捕獲階段')
}, true)
root.addEventListener('click', function(e){
console.log('root---冒泡階段')
}, false)
parent.addEventListener('click', function(e){
console.log('parent---冒泡階段')
}, false)
child.addEventListener('click', function(e){
console.log('child---冒泡階段')
}, false)
實(shí)驗(yàn)一:驗(yàn)證捕獲階段和冒泡階段的執(zhí)行順序
點(diǎn)擊紅區(qū)區(qū)域(target:root層)
root事件.png
點(diǎn)擊黃色區(qū)域(target:parent層)
parent事件.png
點(diǎn)擊藍(lán)色區(qū)域(target:child層)
child事件.png
實(shí)驗(yàn)二:在各個(gè)流程進(jìn)行打斷
a. 僅在root層捕獲階段停止捕獲志膀,點(diǎn)擊root層,root層的事件經(jīng)歷捕獲階段鳖擒,目標(biāo)階段溉浙,冒泡階段
root.addEventListener('click', function(e){
e.stopPropagation()
console.log('root---捕獲階段')
}, true)
事件流程完成.png
b.僅在root層捕獲階段停止捕獲,點(diǎn)擊child層蒋荚,會(huì)在root層結(jié)束捕獲戳稽,并不再向下傳播,整個(gè)事件流終止
root層捕獲階段停止捕獲.png
c.僅在child層冒泡階段停止冒泡期升,點(diǎn)擊child層惊奇,會(huì)在child層結(jié)束冒泡,并不再向上傳播播赁,整個(gè)事件流終止
child層冒泡階段停止冒泡.png
其他
addEventListener可以再一個(gè)dom上綁定多個(gè)元素颂郎,而on-event只能綁定一次,因?yàn)閛n-event只是一個(gè)屬性如下代碼容为,onclick將被覆蓋
child.setAttribute('onclick', "alert('child-first')");
child.onclick = function(){
console.log('child---click')
}
//執(zhí)行child---click