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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:18:04  来源:igfitidea点击:

What is the difference between Event.target, Event.toElement and Event.srcElement?

javascriptjavascript-events

提问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.targetattribute.

使用DOM 事件流事件定位到的对象。事件目标是 属性的值。Event.target

srcElementis 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.currentTargetattribute.

在事件流中,当前事件目标是与当前正在分派的事件处理程序关联的对象。该对象可能是事件目标本身或其祖先之一。当前事件目标随着事件在事件流的各个阶段从一个对象传播到另一个对象而发生变化。当前事件目标是Event.currentTarget属性的值 。

Using thisinside 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 EventTargetrelated to a UI event, depending on the type of event.

用于标识EventTarget与 UI 事件相关的次要事件,具体取决于事件类型。

fromElementand toElementare IE non-standard ways to obtain the relatedTarget.

fromElement并且toElement是 IE 非标准方式来获取relatedTarget.