dom事件冒泡机制
冒泡:html元素触发事件之后会将事件向上冒泡,交给父元素处理,依次向上,直到浏览器窗口window
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#pre {
width: 200px;
height: 200px;
background: #31fdff;
}
#child {
width: 100px;
height: 100px;
background: #bfa;
}
</style>
</head>
<body>
<div id="pre">
<div id="child"></div>
</div>
<script>
document.getElementById('pre').addEventListener('click', function (e) {
console.log('pre');
})
document.getElementById('child').addEventListener('click', function (e) {
console.log('child');
})
window.addEventListener('click', function (e) {
console.log('window');
})
</script>
</body>
</html>
点击child元素,控制台打印结果
冒泡路径
Event.composedPath()返回处理事件的元素对象列表,第一个元素为第一个触发事件的元素,最后一个为window对象
示例
document.getElementById('pre').addEventListener('click', function (e) {
console.log('pre');
console.log(e.composedPath());
})
document.getElementById('child').addEventListener('click', function (e) {
console.log('child');
console.log(e.composedPath());
})
window.addEventListener('click', function (e) {
console.log('window');
console.log(e.composedPath());
})
点击child元素,控制台打印结果
阻断事件向上冒泡
Event.stopPropagation() 阻断事件向父元素冒泡,在当前元素处理之后,父元素不再触发事件
document.getElementById('pre').addEventListener('click', function (e) {
console.log('pre');
console.log(e.composedPath());
})
document.getElementById('child').addEventListener('click', function (e) {
// 阻断事件向上冒泡
e.stopPropagation()
console.log('child');
})
window.addEventListener('click', function (e) {
console.log('window');
console.log(e.composedPath());
})
点击child元素,控制台打印结果
阻断事件同级触发
比如同一个元素注册了两个点击事件处理器,如果在第一个注册的事件处理器中阻断了事件的传播,那么第二个注册的事件处理器就不会再触发
没有阻断统计事件触发示例
document.getElementById('child').addEventListener('click', function (e) {
console.log('child 1');
})
document.getElementById('child').addEventListener('click', function (e) {
console.log('child 2');
})
点击child元素,控制台打印结果
阻断统计事件触发示例
document.getElementById('child').addEventListener('click', function (e) {
e.stopImmediatePropagation()
console.log('child 1');
})
document.getElementById('child').addEventListener('click', function (e) {
console.log('child 2');
})
点击child元素,控制台打印结果