光说不练假把式上demo!
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.father{
width: 500px;
height: 500px;
display: flex;
align-items: center;
justify-content: center;
background-color: aqua;
}
.son{
width: 200px;
height: 200px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="father">father
<div class="son">son</div>
</div>
<script>
var father=document.querySelector('.father')
var son=document.querySelector('.son')
/* addEventListener第三个参数为ture则为捕获 */
father.addEventListener('click',function(){
alert('father')
},true)
son.addEventListener('click',function(){
alert('son')
},true)
/* addEventListener第三个参数为false或省略则为冒泡 */
/* father.addEventListener('click',function(){
alert('father')
},true)
son.addEventListener('click',function(){
alert('son')
},true) */
</script>
</body>
</html>
完整代码打开即可验证!
注意及解释:
1.捕获和冒泡的顺序:
这个顺序很重要!
2.传递的是一个被激活的事件,但是事件函数要看接收方,下面进行验证。
代码:
<div id="father">father
<div id="son">son</div>
</div>
<script>
var father=document.querySelector('#father')
var son=document.querySelector('#son')
father.addEventListener('click',function(){
alert('father')
},true)
son.addEventListener('click',function(){
alert('son')
},true)
</script>
上面代码为捕获。我们点击son发现进行了两词弹出对话框,内容分别为father和son。如果去掉alert(‘son’),会发现只弹出father。
参考文章:
浅谈事件冒泡和事件捕获