共计 1380 个字符,预计需要花费 4 分钟才能阅读完成。
冒泡
事件触发程序由外向外
// addEventListener 第三个参数为 useCapture
// false 为冒泡模式
id3.addEventListener('click', function(event){console.log('capture click id3', event)
}, false)
冒泡拦挡
点击 id3 勾销向外冒泡
// false 为冒泡模式
id3.addEventListener('click', function(event){
event.cancelBubble = true
// event.stopPropagation()}, false)
捕捉
事件触发程序由内向内
// addEventListener 第三个参数为 useCapture
// true 为捕捉模式
id3.addEventListener('click', function(event){console.log('capture click id3', event)
}, true)
残缺代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#id1 {
background: lightblue;
padding: 50px;
}
#id2 {
background: lightyellow;
padding: 50px;
}
</style>
</head>
<body>
<div id='id1'>
id 1
<div id="id2">
id 2
<button id='id3'>id3</button>
</div>
</div>
</body>
<script>
// 事件冒泡
var id1 = document.querySelector('#id1')
var id2 = document.querySelector('#id2')
var id3 = document.querySelector('#id3')
id1.addEventListener('click', function(event){console.log('click id1', event)
})
id2.addEventListener('click', function(event){console.log('click id2', event)
})
id3.addEventListener('click', function(event){console.log('click id3', event)
// event.cancelBubble = true
event.stopPropagation()})
// 事件捕捉
// id1.addEventListener('click', function(event){// console.log('capture click id1', event)
// }, true)
// id2.addEventListener('click', function(event){// console.log('capture click id2', event)
// }, true)
// id3.addEventListener('click', function(event){// console.log('capture click id3', event)
// }, true)
</script>
</html>
正文完
发表至: javascript
2022-06-28