简体   繁体   中英

How to get top (as in locale) attribute of a DIV element using Javascript?

I have a group DIV tags in an HTML page whose location is controlled via several parent/grandparent DIVs. Those parent and grandparent's location is controlled via CSS classes. I need to retrieve the top attribute of the given DIV. Where is it in the DOM or how would I calculate it using Javascript?


Clarification: I need the coordinate value of the top of the DIV object in absolute terms (relative to the window).

Since offsetTop and offsetLeft give you relative position values, you can get the absolute values by traversing up the tree of offsetParent s, aggregating the offsetTop and offsetLeft values of each parent element:

function findPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
    return [curleft,curtop];
  }
}

More detailed information: JavaScript Find position

This would give you the top and left:

myDiv.offsetY
myDiv.offsetX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM