MouseEvent.relatedTarget - Web APIs 编辑
The MouseEvent.relatedTarget
read-only property is the secondary target for the mouse event, if there is one. That is:
Event name | target | relatedTarget |
mouseenter | The EventTarget the pointing device entered to | The EventTarget the pointing device exited from |
mouseleave | The EventTarget the pointing device exited from | The EventTarget the pointing device entered to |
mouseout | The EventTarget the pointing device exited from | The EventTarget the pointing device entered to |
mouseover | The EventTarget the pointing device entered to | The EventTarget the pointing device exited from |
dragenter | The EventTarget the pointing device entered to | The EventTarget the pointing device exited from |
dragexit | The EventTarget the pointing device exited from | The EventTarget the pointing device entered to |
For events with no secondary target, relatedTarget
returns null
.
FocusEvent.relatedTarget
is a similar property for focus events.
Syntax
var target = instanceOfMouseEvent.relatedTarget
Return value
An EventTarget
object or null
.
Example
Try moving your mouse cursor into and out of the red and blue boxes.
HTML
<body id="body">
<div id="outer">
<div id="red"></div>
<div id="blue"></div>
</div>
<p id="log"></p>
</body>
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
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}`;
}
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论