事件冒泡
事件触发阶段,由嵌套深层结构向外部冒泡而出
html
<div Box1>
<div Box2>
<div Box3></div>
</div>
</div>
JS
const Box1 = document.querySelector("div[Box1]").addEventListener("click",()=>{
console.log("This is Box1");
});
const Box2 = document.querySelector("div[Box2]").addEventListener("click",()=>{
console.log("This is Box2");
});
const Box3 = document.querySelector("div[Box3]").addEventListener("click",()=>{
console.log("This is Box3");
});
当点击嵌套结构最深层次的Box3时,会依次触发事件 "The is Box3" "The is Box2" "The is Box1"
当点击嵌套结构最深层次的Box2时,会依次触发事件 "The is Box2" "The is Box1"
使用 Event.stopPropagation() 阻止冒泡或捕获的进一步传播
JS
const Box1 = document.querySelector("div[Box1]").addEventListener("click",()=>{
console.log("This is Box1");
});
const Box2 = document.querySelector("div[Box2]").addEventListener("click",(Event)=>{
Event.stopPropagation();
console.log("This is Box2");
});
const Box3 = document.querySelector("div[Box3]").addEventListener("click",()=>{
console.log("This is Box3");
});
当点击嵌套结构最深层次的Box3时,会依次触发事件 "The is Box3" "The is Box2"
当点击嵌套结构最深层次的Box2时,会触发事件 "The is Box2"
在vue2中,需要使用事件修饰符.stop可以阻止冒泡
SFC
<template>
...
<div>
<div @click.stop='xxxx'>
...
</div>
</div>
</template>
捕获阶段
事件捕获与冒泡是正好相反的,由嵌套最外层结构向内触发事件
JS
const Box1 = document.querySelector("div[Box1]").addEventListener("click",()=>{
console.log("This is Box1");
},{
capture:true
}
);
const Box2 = document.querySelector("div[Box2]").addEventListener("click",()=>{
console.log("This is Box2");
},{
capture:true
}
);
const Box3 = document.querySelector("div[Box3]").addEventListener("click",()=>{
console.log("This is Box3");
});
当点击嵌套结构最深层次的Box3时,会依次触发事件 "The is Box1" "The is Box2" "The is Box3"
当点击嵌套结构最深层次的Box2时,会触发事件 "The is Box1" "The is Box2"
在vue2中,需要使用事件修饰符.capture可以阻止冒泡
SFC
<template>
...
<div>
<div @click.capture='xxxx'>
...
</div>
</div>
</template>