上图中重点看第三点
代码:
<!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>
div{
width: 200px;
height: 200px;
background-color: violet;
}
</style>
</head>
<body>
<div></div>
<script>
var div=document.querySelector('div')
div.addEventListener('click',function(e){
console.log(e)
})
</script>
</body>
</html>
效果:
注意事项:
1.e.target返回的是触发事件的对象,而this返回的是绑定事件的对象
代码:
<!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(e){
alert('father');
console.log(e.target);
console.log(this);
},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>
效果: