gpt4 book ai didi

javascript - Event.target、Event.toElement 和 Event.srcElement 之间有什么区别?

转载 作者:IT王子 更新时间:2023-10-29 02:50:19 30 4
gpt4 key购买 nike

我有以下代码:

document.oncontextmenu = function(evt) {
evt = evt || window.event;
console.log(evt.target, evt.toElement, evt.srcElement);
};

通过在 <div class="foo"></div> 上单击鼠标右键,返回这个:

div.foo, div.foo, div.foo

通过在 <input> 上单击鼠标右键,返回这个:

input, input, input

所有似乎都带来相同的结果。是否存在其中一个与其他用途不同的情况?

最佳答案

event target是事件被分派(dispatch)到的元素:

The object to which an event is targeted using the DOM event flow. The event target is the value of the Event.target attribute.

srcElement是IE非标准的获取target的方式。

current event target是具有当前调用的事件监听器的元素:

In an event flow, the current event target is the object associated with the event handler that is currently being dispatched. This object MAY be the event target itself or one of its ancestors. The current event target changes as the event propagates from object to object through the various phases of the event flow. The current event target is the value of the Event.currentTarget attribute.

在事件监听器中使用 this 是获取当前事件目标的常见(标准)方法。

有些事件有一个 relatedTarget :

Used to identify a secondary EventTarget related to a UI event, depending on the type of event.

fromElementtoElement 是IE 获取relatedTarget 的非标准方式。

关于javascript - Event.target、Event.toElement 和 Event.srcElement 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31865416/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com