--- title: event.relatedTarget slug: Web/API/event.relatedTarget translation_of: Web/API/MouseEvent/relatedTarget translation_of_original: Web/API/event.relatedTarget ---
{{APIRef("DOM")}}
为事件标识第二目标
relatedTarget
属性用于在一个事件中查找另外一个元素。有些事件比如 mouseover
通常侧重处理一个特定的目标,而有些有也可能会涉及到第二目标,比如当目标退出第一目标的 mouseover
事件.
只有 MouseEvent
s 有这个属性,而且这些些只在特定的 MouseEvent
s 事件中有效:
事件名 | relatedTarget role |
focusin | 哪个 {{domxref("EventTarget")}} 失去焦点 |
focusout | 哪个 {{domxref("EventTarget")}} 获得焦点 |
mouseenter | 鼠标从哪个 {{domxref("EventTarget")}} 进来 |
mouseleave | 鼠标移到哪个{{domxref("EventTarget")}} 去 |
mouseout | 鼠标移到哪个{{domxref("EventTarget")}} 去 |
mouseover | 鼠标从哪个{{domxref("EventTarget")}} 进来 |
dragenter | 鼠标从哪个{{domxref("EventTarget")}} 进来 |
dragexit | 鼠标移到哪个{{domxref("EventTarget")}} 去 |
<!DOCTYPE html> <html> <head> <style> div > div { height: 128px; width: 128px; } #top { background-color: red; } #bottom { background-color: blue; } </style> <script> function outListener(event) { console.log("exited " + event.target.id + " for " + event.relatedTarget.id); } function overListener(event) { console.log("entered " + event.target.id + " from " + event.relatedTarget.id); } function loadListener() { var top = document.getElementById("top"), bottom = document.getElementById("bottom"); top.addEventListener("mouseover", overListener); top.addEventListener("mouseout", outListener); bottom.addEventListener("mouseover", overListener); bottom.addEventListener("mouseout", outListener); } </script> </head> <body onload="loadListener();"> <div id="outer"> <div id="top"></div> <div id="bottom"></div> </div> </body> </html>