MouseEvent.relatedTarget

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

io error: No such file or directory (os error 2) (/home/runner/work/yari/yari/mdn/translated-content/files/zh-cn/web/api/ui_events/index.md)

只读属性 MouseEvent.relatedTarget 是鼠标事件的次要目标(如果存在),它包括:

事件名称 target relatedTarget
focusin EventTarget 获取焦点 EventTarget 失去焦点
focusout EventTarget 失去焦点 The EventTarget 获取焦点
mouseenter 指针设备进入EventTarget 指针设备离开EventTarget
mouseleave 指针设备离开 EventTarget 指针设备进入 EventTarget
mouseout 指针设备离开 EventTarget The EventTarget
mouseover 指针设备进入 EventTarget 指针设备离开 EventTarget
dragenter 指针设备进入 EventTarget 指针设备离开 EventTarget

如果事件没有次要目标,relatedTarget 将返回 null.

EventTarget 对象或者 null.

示例

尝试将你的鼠标移入移出红色和蓝色方块。

HTML

html
<body id="body">
  <div id="outer">
    <div id="red"></div>
    <div id="blue"></div>
  </div>
  <p id="log"></p>
</body>

CSS

css
#outer {
  width: 250px;
  height: 125px;
  display: flex;
}

#red {
  flex-grow: 1;
  background: red;
}

#blue {
  flex-grow: 1;
  background: blue;
}

#log {
  max-height: 120px;
  overflow-y: scroll;
}

JavaScript

js
const mouseoutLog = document.getElementById("log"),
  red = document.getElementById("red"),
  blue = document.getElementById("blue");

red.addEventListener("mouseover", overListener);
red.addEventListener("mouseout", outListener);
blue.addEventListener("mouseover", overListener);
blue.addEventListener("mouseout", outListener);

function outListener(event) {
  let related = event.relatedTarget ? event.relatedTarget.id : "unknown";

  mouseoutLog.innerText = `\nfrom ${event.target.id} into ${related} ${mouseoutLog.innerText}`;
}

function overListener(event) {
  let related = event.relatedTarget ? event.relatedTarget.id : "unknown";

  log.innerText = `\ninto ${event.target.id} from ${related} ${mouseoutLog.innerText}`;
}

结果

规范

Specification
UI Events
# dom-mouseevent-relatedtarget

浏览器兼容性

BCD tables only load in the browser

参见