Getting DIV id based on x & y position

后端 未结 9 830
渐次进展
渐次进展 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:24
    function getDivByXY(x,y) {
       var alldivs = document.getElementsByTagName('div');
    
       for(var d = 0; d < alldivs.length; d++) {
          if((alldivs[d].offsetLeft == x) && (alldivs[d].offsetTop == y)) {
             return alldivs[d];
          }
       }
    
       return false;
    }
    
    0 讨论(0)
  • 2020-12-06 12:27

    Create a mouse event listener, then trigger a mouse event at that location. This should give you the entire stack of elements at that location.

    Or, look at the source of Firebug.

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

    If all you have is the X and Y position, (and you can't track mouse movement like you mentioned) then you will have to traverse the DOM, looping through every DIV. For each DIV you will need to compare its X and Y coordinates against those you have. This is an expensive operation, but it is the only way. I suggest you might be better off rethinking your problem instead of coming up with a solution for it.

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

    this might be a little too processor intensive but going over the whole list of div elements on a page, finding their positions and sizes then testing if they're under the mouse. i don't think i'd want to do that to a browser though.

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

    One option is to build an array of "div-dimension" objects. (Not to be confused with the divs themselves... IE7 perf is frustrating when you read dimensions off of object.)

    These objects consist of a pointer to the div, their dimensions (four points... say top, left, bottom, and right), and possibly a dirty bit. (Dirty bit is only really needed if the sizes change.

    You could then iterate through the array and check dimensions. It requires O(n) to do that on each mouse move. You might be able to do slightly better with a binary search style approach... maybe.

    If you do a binary search style approach, one way is to store 4 arrays. Each with a single point of the dimension, and then binary search on all four. O(4logn) = O(logn).

    I'm not saying I recommend any of these, but they MIGHT work.

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

    I think what John is saying is that you can use document.createEvent() to simulate a mousemove at the location you want. If you capture that event, by adding an eventlistener to the body, you can look at the event.target and see what element was at that position. I'm unsure as to what degree IE supports this method, maybe someone else knows?

    http://developer.mozilla.org/en/DOM/document.createEvent

    Update: Here's a jquery plugin that simulates events:

    http://jquery-ui.googlecode.com/svn/trunk/tests/simulate/jquery.simulate.js

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