target、currentTarget都是2级DOM事件标准定义的属性,在Vue、微信小程序开发中经常使用,它们有什么区别呢?先看一段转载的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>target VS currentTarget</title>
<style type="text/css" rel="stylesheet">
#fa{
width: 100%;
height: 170px;
padding: 20px 0px;
background-color: cadetblue;
}
#son{
width: 100%;
height: 20px;
padding: 30px 0px;
background-color: black;
color: white;
text-align: center;
cursor: pointer;
}
</style>
</head>
<body>
<div id="fa" onmousedown="getEventTrigger(event)">
<p id="son" onmousedown="getEventTrigger(event)">点我试试</p>
</div>
</body>
<script type="text/javascript">
var fa = document.getElementById('fa');
var son = document.getElementById('son');
function getEventTrigger(event) {
x=event.currentTarget;
y=event.target;
alert("currentTarget 指向: " + x.id + ", target指向:" + y.id);
}
</script>
</html>
通过浏览器查看,当点击黑色区域,由于“事件冒泡”,会弹出两个提示框,分别为:
currentTarget 指向: son, target指向:son => 点击的对象id为son,触发了id为son的对象所注册的某个事件
currentTarget 指向: fa, target指向:son => 点击的对象id为son,由于事件冒泡,触发了id为fa的对象所注册的某个事件
当点击军校蓝区域,会弹出一个提示框:
currentTarget 指向: fa, target指向:fa => 点击的对象id为fa,触发了id为fa的对象所注册的某个事件