简体   繁体   English

检测鼠标从哪一侧离开div

[英]Detect from which side the mouse left a div

I modified the code of the best answer of another question (which aimed to detect from which side the mouse entered a div ) in order to make it detect from which side the mouse left a div . 我修改了另一个问题(旨在检测鼠标从哪一侧进入 div )的最佳答案的代码,以使其能够检测到鼠标div一侧离开div

Here is the my code . 这是我的代码 I changed the log to display in the console. 我更改了日志以显示在控制台中。 But somehow the results are always being "right" or "bottom" and no "top" or "left". 但是结果总是以“右”或“下”而不是“上”或“左”的形式出现。

Any advise, please? 有什么建议吗?

I've been working a bit on the code and I've modified some stuff. 我已经在代码上做了一些工作,并且已经修改了一些东西。

Since you're positioning your div with absolute position, you need to check the position on a different way. 由于您将div定位为绝对位置,因此需要以其他方式检查位置。

First, I'm using getBoundingClientRect() which returns the position of the element (left, top, right and bottom). 首先,我使用getBoundingClientRect()返回元素的位置(左,上,右和下)。

Then I get the mouse coordinates and I calculate from which edge is closest. 然后,我得到了鼠标坐标,并计算出从哪个边缘最近。

You can see an example of my code here: 您可以在此处查看我的代码示例:

 document.querySelector('#content').onmouseleave = function(mouse) { var edge = closestEdge(mouse, this); console.log(edge); } function closestEdge(mouse, elem) { var elemBounding = elem.getBoundingClientRect(); var elementLeftEdge = elemBounding.left; var elementTopEdge = elemBounding.top; var elementRightEdge = elemBounding.right; var elementBottomEdge = elemBounding.bottom; var mouseX = mouse.pageX; var mouseY = mouse.pageY; var topEdgeDist = Math.abs(elementTopEdge - mouseY); var bottomEdgeDist = Math.abs(elementBottomEdge - mouseY); var leftEdgeDist = Math.abs(elementLeftEdge - mouseX); var rightEdgeDist = Math.abs(elementRightEdge - mouseX); var min = Math.min(topEdgeDist,bottomEdgeDist,leftEdgeDist,rightEdgeDist); switch (min) { case leftEdgeDist: return "left"; case rightEdgeDist: return "right"; case topEdgeDist: return "top"; case bottomEdgeDist: return "bottom"; } } 
 #content { width: 100px; height: 100px; background: lightblue; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } 
 <div id="content"></div> 

I hope that helps you. 希望对您有所帮助。

Cheers! 干杯!

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

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