Javascript Event.target、Event.toElement 和 Event.srcElement 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31865416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between Event.target, Event.toElement and Event.srcElement?
提问by Guilherme Nascimento
I have the following code:
我有以下代码:
document.oncontextmenu = function(evt) {
evt = evt || window.event;
console.log(evt.target, evt.toElement, evt.srcElement);
};
By clicking the right mouse button on a <div class="foo"></div>
, returns this:
通过在 a 上单击鼠标右键<div class="foo"></div>
,返回:
div.foo, div.foo, div.foo
div.foo, div.foo, div.foo
By clicking the right mouse button on a <input>
, returns this:
通过在 a 上单击鼠标右键<input>
,返回:
input, input, input
输入,输入,输入
All seem to bring the same result. Is there any situation that one of them has different use than the others?
一切似乎都带来了相同的结果。是否存在其中一个与其他用途不同的情况?
回答by Oriol
The event targetis the element to which the event is dispatched:
该活动的目标是到该事件被分派的元素:
The object to which an eventis targeted using the DOM event flow. The event target is the value of the
Event.target
attribute.
使用DOM 事件流将事件定位到的对象。事件目标是 属性的值。
Event.target
srcElement
is a IE non-standard way to obtain the target
.
srcElement
是一种 IE 非标准方式来获取target
.
The current event targetis the element which has the event listener which is currently invoked:
的当前事件的目标是具有当前正在调用的事件侦听器的元件:
In an event flow, the current event target is the object associated with the event handlerthat is currently being dispatched. This object MAY be the event targetitself or one of its ancestors. The current event target changes as the eventpropagates from object to object through the various phasesof the event flow. The current event target is the value of the
Event.currentTarget
attribute.
在事件流中,当前事件目标是与当前正在分派的事件处理程序关联的对象。该对象可能是事件目标本身或其祖先之一。当前事件目标随着事件在事件流的各个阶段从一个对象传播到另一个对象而发生变化。当前事件目标是
Event.currentTarget
属性的值 。
Using this
inside an event listener is a common (and standard) way to obtain the current event target.
this
在事件侦听器内部使用是获取当前事件目标的常用(和标准)方式。
Some kind events have a relatedTarget
:
一些种类的事件有relatedTarget
:
Used to identify a secondary
EventTarget
related to a UI event, depending on the type of event.
用于标识
EventTarget
与 UI 事件相关的次要事件,具体取决于事件类型。
fromElement
and toElement
are IE non-standard ways to obtain the relatedTarget
.
fromElement
并且toElement
是 IE 非标准方式来获取relatedTarget
.