Getting DIV id based on x & y position

后端 未结 9 831
渐次进展
渐次进展 2020-12-06 11:52

The problem I\'m trying to solve is \"What\'s at this position?\"

It\'s fairly trivial to get the x/y position (offset) of a DIV, but what about the reverse? How do

相关标签:
9条回答
  • 2020-12-06 12:43

    Unfortunately, triggering a manufactured/simulated mouse event won't work, since when you dispatch it, you have to provide a target element. Since that element is the one you're trying to figure out, all you could do is dispatch it on the body, as if it had already bubbled.

    You really are left to do it on your own, that is manually walk through the elements you're interested in, and compare their position/size/zIndex to your x/y point and see if they overlap. Except in IE and more recently FF3, where you can use

    var el = document.elementFromPoint(x, y);
    

    See

    http://developer.mozilla.org/En/DOM:document.elementFromPoint

    http://msdn.microsoft.com/en-us/library/ms536417(VS.85).aspx

    0 讨论(0)
  • 2020-12-06 12:47

    Use a JQuery selector to filter the list of all DIVs for one that matches your position criteria?

    0 讨论(0)
  • 2020-12-06 12:48

    You might find it's more efficient to traverse the DOM tree once when the page is loaded, get all elements' positions and sizes, and store them in an array/hash/etc. If you design the data structure well, you should be able to find an element at the given coordinates fairly quickly when you need it later.

    Consider how often you will need to detect an element, and compare that to how often the elements on the page will change. You would be balancing the number of times you have to re-compute all the element locations (an expensive computation) against the number of times you'd actually use the computed information (relatively cheap, I hope).

    0 讨论(0)
提交回复
热议问题