简体   繁体   English

仅顶部的 MouseOut 事件

[英]MouseOut Event from ONLY the top

I am trying to use the mouseOut event handler, but I want to restrain the event to fire when the mouse exits from the TOP ONLY——not from the right, left or bottom.我正在尝试使用 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();

What can I add to make it only fire when the mouseOut is from the top of my element ?我可以添加什么以使其仅在 mouseOut 来自元素顶部时触发?

You can check if clientY is smaller than the offsetTop from your element.您可以检查clientY是否小于元素的offsetTop
Only if the mouse cursor leaves on the top, this is the case只有当鼠标光标离开顶部时,才会出现这种情况

 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>


edit编辑

non arrow function for IE 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM