最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - event.target vs event.relatedTarget - Stack Overflow

programmeradmin3浏览0评论

I want to know the difference between event.target and event.relatedTarget. The following is a code chunk from drag and drop activity.

  ondragleave: function (event) {
    // remove the drop feedback style
    event.target.classList.remove('drop-target');
    event.relatedTarget.classList.remove('can-drop');
    event.relatedTarget.textContent = 'Dragged out';

  }

I want to know the difference between event.target and event.relatedTarget. The following is a code chunk from drag and drop activity.

  ondragleave: function (event) {
    // remove the drop feedback style
    event.target.classList.remove('drop-target');
    event.relatedTarget.classList.remove('can-drop');
    event.relatedTarget.textContent = 'Dragged out';

  }

Share Improve this question asked Oct 25, 2016 at 5:15 Syed HaiderSyed Haider 1031 gold badge1 silver badge4 bronze badges 3
  • 5 developer.mozilla.org/en-US/docs/Web/API/MouseEvent/… – Evan Trimboli Commented Oct 25, 2016 at 5:16
  • Or explicitly for dragleave: developer.mozilla.org/en-US/docs/Web/Events/dragleave – Andreas Commented Oct 25, 2016 at 5:33
  • want to know the difference between event.target and event.relatedTarget. - so what is your question? – Max Koretskyi Commented Oct 25, 2016 at 5:35
Add a comment  | 

1 Answer 1

Reset to default 18

The relatedTarget event target is used by some events to specify a secondary target. On the other hand, target will be used by most DOM events to specify the primary target of an event.

For instance, during focus events, target will be the element gaining focus, and relatedTarget will be the element losing focus.

You can check out an exhaustive list of DOM events that specify a relatedTarget here: MouseEvent.relatedTarget.

As answered here

So judging from the above explanation we can say that

<div class="outer">
  <div class="inner"></div>
</div>

In this example, when you hover inside the inner div, then in the handler:

  • event.target refers to the .inner element (this gives you the element where the event originated)
  • event.relatedTarget refers to the .outer element (this gives you the element that receives the focus first and the loose the focus to other element)

you can check this fiddle for better understanding


Now in your own scenario

ondragleave: function (event) {
    /*when the dragged element leaves the drop target, remove the 
    .drop-target class from the current focused element*/
    event.target.classList.remove('drop-target');
    
    /*remove the .can-drop class from the element that looses focus 
    to the current focused element and changed the text to Dragged Out*/
    event.relatedTarget.classList.remove('can-drop');
    event.relatedTarget.textContent = 'Dragged out';

  }

Thanks.

发布评论

评论列表(0)

  1. 暂无评论