gpt4 book ai didi

javascript - 仅顶部的 MouseOut 事件

转载 作者:行者123 更新时间:2023-11-29 20:42:18 24 4
gpt4 key购买 nike

我正在尝试使用 mouseOut 事件处理程序,但我想限制事件仅在鼠标从顶部退出时触发——而不是从右侧、左侧或底部退出。

var executed = false;

function mouseoutHandler(e){
window.removeEventListener("mouseout", mouseoutHandler, false);
executed = true;
document.getElementById(“element”).style.width = "300px";
}

function runOnce() {
window.addEventListener("mouseout", mouseoutHandler, false);
};


runOnce();

我可以添加什么以使其仅在 mouseOut 位于元素顶部时才触发?

最佳答案

您可以检查 clientY 是否小于元素中的 offsetTop
只有当鼠标光标离开顶部时,才会出现这种情况

const myElement = document.getElementById('element');
var executed = false;

const mouseoutHandler = (e) => {
if(e.clientY <= myElement.offsetTop) {
myElement.style.width = '100px';
executed = true;
myElement.removeEventListener('mouseout', mouseoutHandler);
}
}

myElement.addEventListener('mouseout', mouseoutHandler, false);
body{height:100vh;display:flex;justify-content:center;align-items:center}#element{width:200px;height:100px;background:#333}
<div id="element">&nbsp;</div>


编辑

IE 的非箭头函数

var myElement = document.getElementById('element');
var executed = false;

function mouseoutHandler(e) {
if(e.clientY <= myElement.offsetTop) {
myElement.style.width = '100px';
executed = true;
myElement.removeEventListener('mouseout', mouseoutHandler);
}
}

myElement.addEventListener('mouseout', mouseoutHandler, false);
body{height:100vh;display:flex;justify-content:center;align-items:center}#element{width:200px;height:100px;background:#333}
<div id="element">&nbsp;</div>

关于javascript - 仅顶部的 MouseOut 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com