每一个点击事件都会有一个event对象,每一个event对象都有一个target和currentTarget属性,它们有什么区别呢?
上代码
// html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {
padding-left: 200px;
}
div {
border: 1px solid #777;
height: 300px;
width: 300px;
}
button {
margin: 100px;
}
</style>
</head>
<body>
<button onclick="clickFun1();">click</button>
<div onclick="clickFun2();">
<button>click2</button>
</div>
</body>
</html>
// js代码
<script>
function clickFun1() {
console.log('target', event.target);
console.log('currentTarget', event.currentTarget);
}
function clickFun2() {
console.log('target', event.target);
console.log('currentTarget', event.currentTarget);
}
</script>
- 点击button1时,target和currentTarget都指向了button按钮
- 点击button2时,target指向button标签,currentTarget指向了div标签
- 点击button2所在div时,target和currentTarget都指向了div标签
总结
- target指向的是你点击的标签
- currentTarget指向的是你绑定事件的标签
- 当绑定事件的标签和点击的标签一致时,target和currentTarget指向了同一个标签