元素偏移始终为0

时间:2013-12-06 21:26:57

标签: javascript jquery

当点击链接时,我正在使用带有链接列的表我想获得行的偏移量。我尝试使用element.offsetTop和$(element).offset()。top并且返回0,父元素也返回0作为它们的偏移顶部。

我试过了

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;
}

但是这仍然为y pos返回0。

4 个答案:

答案 0 :(得分:8)

以下函数遍历DOM树,计算路径上的位置。它返回一个.x.y作为属性的对象,因此getPosition(element).y会为您提供页面顶部的像素数。

   /**
   * 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) };
  }

希望这会有所帮助;)

答案 1 :(得分:2)

offsetParent取决于您的样式。 See here它明确指出offsetParent在某些情况下可能会返回null。您应该检查这些情况。

如果你有jquery我会建议使用它们的偏移函数来获得y偏移量。 Offset API here

if语句中的while循环也是多余的。你不需要if,因为你的while循环评估相同的东西,如果那个条件是假的话就不会执行。

答案 2 :(得分:0)

我只是碰到了这个问题,而罪魁祸首是我在父元素之一中添加了contain: content;,这显然影响了.offsetTop值。

答案 3 :(得分:0)

对于到达这里的任何人,我建议使用 getBoundingClientRect() 获取元素相对于文档的顶部和左侧位置,或者获取元素的大小及其相对于视口的位置。< /p>

  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;