Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

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

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:

div.foo, div.foo, div.foo

By clicking the right mouse button on a <input>, returns this:

input, input, input

All seem to bring the same result. Is there any situation that one of them has different use than the others?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The event target is the element to which the event is dispatched:

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 is a IE non-standard way to obtain the target.

The current event target is 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 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.

Using this inside an event listener is a common (and standard) way to obtain the current event target.

Some kind events have a relatedTarget:

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

fromElement and toElement are IE non-standard ways to obtain the relatedTarget.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...