How can I detect the element(s) at an arbitrary mouse position (x,y)? [duplicate]
Possible Duplicate:
Get element at specified position - JavaScript
How can I detect the elements at an arbitrary mouse position (x,y)?
I am using mouseenter
/mouseleave
to highlight hovered items. Unfortunately neither of these fire when the mouse moves implicitly and this leads to the wrong item being highlighted. An example of moving the mouse implicitly would be scrolling the page with arrow keys or track pad.
You can see a working demo with comments here: http://jsfiddle.net/bkG2K/6/
My idea for a workaround is to check the mouse's position every so often, or just after scrolling if possible, and update the hover state based on the current mouse co-ordinates. But I'm not sure how I can find DOM elements given an X,Y.
Ideas? If开发者_如何转开发 you have a better solution to the root problem, feel free!
You can use the native JavaScript elementFromPoint(x, y)
method, that returns the element at coordinates x,y in the viewport.
See the elementFromPoint w3c draft
And, a code sample:
<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>
You can use setInterval()
to continuously check the element's hover event but it's not recommended, try to use .hover(...)
and css instead to enhance the application performance.
I don't know if internal implementations differ, but for what you are trying to achieve the intended method would be .hover(...)
which takes two callbacks to execute in each state-change.
Alternatively, you could setInterval()
and simulate .mousemove()
event at the cursor's position (Though you should do a broswer check and only use it in the problematic browser since this is kind of a hack, and as few as possible people should be exposed to it)
精彩评论