其实真正搞懂这两者之间的关系,只需要用代码做下实验就好了,其实很简单。请一定耐心看下去,您会彻底搞懂这两者的关系。
总结:e.curretnTarge是指注册了事件监听器的对象,也就是其事件处理程序当前正在处理事件的那个对象。e.target是指实际触发这个事件的源对象。
HTML:
<div class="parent">
<div class="child">
<div class="grandchild"></div>
</div>
</div>
CSS:
.parent{
width: 300px;
height: 300px;
background-color: #bfa;
}
.child{
width: 200px;
height: 200px;
background-color: red;
}
.grandchild{
width: 100px;
height: 100px;
background-color: blue;
}
Javascript:
const parent=document.getElementsByClassName("parent")[0]
const child=document.getElementsByClassName("child")[0]
const grandchild=document.getElementsByClassName("grandchild")[0]
grandchild.onclick=function(event){
console.log(event.target )
console.log(event.currentTarget )
}
child.onclick=function(event){
console.log(event.target )
console.log(event.currentTarget )
}
parent.onclick=function(event){
console.log(event.target )
console.log(event.currentTarget )
}
点击parent的输出:
当捕获阶段捕获到实际触发这个事件的原对象时,事件处理程序正在处理parent这个对象,故currentTarget是parent这个对象。
而实际触发这个事件也是parent对象。故target也是这个parent对象。
点击child的输出 :
当捕获阶段捕获到实际触发这个事件的原对象时,事件处理程序正在处理child这个对象,故currentTarget是child这个对象。
而实际触发这个事件也是child对象。故target也是这个child对象。
随后事件开始冒泡到父元素parent身上,事件处理程序正在处理parent这个对象,故currentTarget是parent这个对象。
而实际触发这个事件是child对象,不是parent对象,parent对象的事件是child元素冒泡得来的。故target是这个child对象,不是parent对象。
点击grandchild的输出:
当捕获阶段捕获到实际触发这个事件的原对象时,事件处理程序正在处理grandchild这个对象,故currentTarget是grandchild这个对象。
而实际触发这个事件也是grandchild对象。故target也是这个grandchild对象。
随后事件开始冒泡到父元素 child身上,事件处理程序正在处理child这个对象,故currentTarget是child这个对象。
而实际触发这个事件是grandchild对象,不是child对象,child对象的事件是grandchild元素冒泡得来的。故target是这个grandchild对象,不是child对象。
随后事件又开始冒泡到child的父元素 parent身上,事件处理程序正在处理parent这个对象,故currentTarget是parent这个对象。
而实际触发这个事件是grandchild对象,不是parent对象,也不是child对象,child对象的事件是grandchild元素冒泡得来的,而parent对象的事件是从child元素冒泡得来的,相当于是从grandchild冒泡得来的。故此时target是这个grandchild对象,不是child对象,更不是parent对象。