【问题标题】:How can I detect the element(s) at an arbitrary mouse position (x,y)? [duplicate]如何检测任意鼠标位置(x,y)的元素? [复制]
【发布时间】:2011-09-07 00:14:32
【问题描述】:
【问题讨论】:
标签:
javascript
jquery
dom-events
mouseover
mouseout
【解决方案1】:
您可以使用原生 JavaScript elementFromPoint(x, y) 方法,该方法返回视口中坐标 x,y 处的元素。
见elementFromPoint w3c draft
还有一个代码示例:
<html>
<head>
<title>elementFromPoint example</title>
<script type="text/javascript">
function changeColor(newColor)
{
elem = document.elementFromPoint(2, 2);
elem.style.color = newColor;
}
</script>
</head>
<body>
<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
</body>
</html>
您可以使用setInterval()不断检查元素的悬停事件但不推荐,尝试使用.hover(...)和css代替以增强应用程序性能。
【解决方案2】:
我不知道内部实现是否不同,但对于您想要实现的预期方法是.hover(...),它需要在每个状态更改中执行两个回调。
或者,您可以setInterval() 并在光标位置模拟.mousemove() 事件(尽管您应该进行浏览器检查并仅在有问题的浏览器中使用它,因为这是一种黑客行为,并且尽可能少的人应该暴露给它)