How do I find the DOM node that is at a given (X,Y) position? (Hit test)

江枫思渺然 提交于 2019-11-27 11:42:31
Crescent Fresh

As long as your users aren't using old versions of Safari, Chrome or Opera, you're in luck: use document.elementFromPoint(x, y) (MSDN ref, Mozilla ref, QuirksMode article):

Returns the element from the document ... which is the topmost element which lies under the given point.

If you need to support older browsers, I can't think of many options other than what you suggest (traverse the entire DOM, looking at element positions and sizes and seeing if any of them encapsulate your (x, y)).

I don't think the event simulation will work but it is an interesting idea. My understanding of event dispatching is you specify the target that the event is for, which is precisely what you are trying to find out in the first place.

In IE exist document.body.componentFromPoint(x,y). I don't know if there is a cross browser implementation.

This is probably not the best solution, but you can traverse the dom tree starting with finding co-ordinates of ancestor nodes that contains your x and y positions and quickly get to the leaf node that contains your co-ordinates. For getting the positions of a node in a cross browser way you can look at the JS toolkits. One that I have used is dojo. Take a look at dojo._getMarginBox here

document.elementFromPoint(x,y)

Documented here for Firefox 3 and here for IE, but see quirksmode for cross-browser differences.

You can use jQuery for that. I'd bind all needed dom elements to the click event, this will give me appropriate dom object on click as well as mouse position.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!