admin管理员组

文章数量:1178529

I am using a table with a link column when the link is clicked i would like to get the offset of the row. I tried using element.offsetTop and $(element).offset().top and both return 0 the parent elements also return 0 as their offset top.

I have tried

function getTop(element)
{
   var top = findPosY(element);
   console.log(top); 
}

function findPosY(obj) {
   var curtop = 0;
   if (obj.offsetParent) {
      while (obj.offsetParent) {
         curtop += obj.offsetTop
         obj = obj.offsetParent;
      }
   }
   else if (obj.y)
     curtop += obj.y;
   return curtop;
}

but this still return 0 for the y pos.

I am using a table with a link column when the link is clicked i would like to get the offset of the row. I tried using element.offsetTop and $(element).offset().top and both return 0 the parent elements also return 0 as their offset top.

I have tried

function getTop(element)
{
   var top = findPosY(element);
   console.log(top); 
}

function findPosY(obj) {
   var curtop = 0;
   if (obj.offsetParent) {
      while (obj.offsetParent) {
         curtop += obj.offsetTop
         obj = obj.offsetParent;
      }
   }
   else if (obj.y)
     curtop += obj.y;
   return curtop;
}

but this still return 0 for the y pos.

Share Improve this question asked Dec 6, 2013 at 21:26 archonarchon 3911 gold badge2 silver badges9 bronze badges 2
  • It sounds like neither statements are true, so it returns 0. That or obj.y = 0, and offsetTop = 0. – Sterling Archer Commented Dec 6, 2013 at 21:30
  • Can you also post your HTML? And possibly jsfiddle to reproduce issue? – suff trek Commented Dec 6, 2013 at 21:34
Add a comment  | 

6 Answers 6

Reset to default 10

The following function walks up the DOM tree, calculating the positions on its way. It returns an object with .x and .y as properties, so getPosition(element).y will give you the number of pixels from the top of the page.

   /**
   * returns the absolute position of an element regardless of position/float issues
   * @param {HTMLElement} el - element to return position for 
   * @returns {object} { x: num, y: num }
   */
  function getPosition(el) {

    var x = 0,
        y = 0;

    while (el != null && (el.tagName || '').toLowerCase() != 'html') {
        x += el.offsetLeft || 0; 
        y += el.offsetTop || 0;
        el = el.parentElement;
    }

    return { x: parseInt(x, 10), y: parseInt(y, 10) };
  }

Hope this helps ;)

offsetParent is dependent on your styles. See here It clearly states that offsetParent may return null in certain circumstances. You should check for those cases.

If you have jquery I would recommend using their offset function to get the y offset. Offset API here

Also your while loop inside the if-statement is redundant. You do not need the if since your while loop evaluates the same thing and will not execute if that condition is false.

For anyone who lands here I'd suggest to use getBoundingClientRect() to get the top and left position of an element relative to the document or to get the size of an element and its position relative to the viewport.

  var div = document.getElementById("myDiv");
  var rect = div.getBoundingClientRect();
  x = rect.left;
  y = rect.top; // how far from the top of the view port
  w = rect.width;
  h = rect.height;

I just ran into this, and the culprit was that I had added contain: content; to one of the parent elements, which apparently affects the .offsetTop values.

what John posted is good but offsetTop and offsetLeft id distance to the last relative position. this computes redundant distance. i made some changes and it works fine now:

/**
 * returns the absolute position of an element regardless of position/float issues
 * @param {HTMLElement} el - element to return position for
 * @returns {object} { x: num, y: num }
 */
function getPosition(el) {
  let x = 0, y = 0, n = true;

  do {
    if (n) {
      x += el.offsetLeft || 0
      y += el.offsetTop || 0
      n = false
    } else if (getComputedStyle(el).position === "relative") {
      n = true
    }
    el = el.parentElement;
  } while (el != null && (el.tagName || '').toLowerCase() !== 'html');

  return {x: parseInt(x, 10), y: parseInt(y, 10)};
}

I've found that this is a simple and reliable solution:

window.pageYOffset + element.getBoundingClientRect().y

  • window.pageYOffset is how far down the page is scrolled. This assumes the scrolling container is the page itself, and not an element lower in the element tree. You might also need to change window by document.body.
  • element.getBoundingClientRect().y is the y position of the element, but relative to the scroll position. The closer you scroll to the element, the smaller this number becomes (take into account that this could potentially be a negative number!).

本文标签: javascriptElement offset is always 0Stack Overflow