javascript 元素偏移始终为 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20433868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:28:54  来源:igfitidea点击:

Element offset is always 0

javascriptjquery

提问by archon

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.

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

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.

但这仍然为 y 位置返回 0。

回答by John Doherty

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

以下函数沿着 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) };
  }

Hope this helps ;)

希望这可以帮助 ;)

回答by johnsoe

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

offsetParent 取决于您的样式。见这里它清楚地说明了 offsetParent 在某些情况下可能会返回 null。您应该检查这些情况。

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

如果你有 jquery,我会推荐使用他们的 offset 函数来获取 y 偏移量。偏移 API 在这里

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.

此外,if 语句中的 while 循环也是多余的。您不需要 if 因为您的 while 循环评估相同的内容并且如果该条件为假则不会执行。

回答by Shane McCurdy

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.

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