为什么 window.scrollY + element.getBoundingClientRect().top 不等于 element.offsetTop?

Why window.scrollY + element.getBoundingClientRect().top is not equal to element.offsetTop?

我预计 element.getBoundingClientRect()window.scrollYelement.offsetTop 会如下图所示工作。但是正如您所看到的,数字并没有加起来(在我的例子中,pos.offsetTop - (el.getBoundingClientRect().top + window.scrollY) 总是 == -14)。

我做错了什么?

这可能是由于您的网页结构所致。如果你看下面的例子,你会发现内部 div 的 offsetTop 仍然是 51,即使它距离页面顶部超过 150px。

var element = document.getElementById("id");
console.log(element.offsetTop)
<table style="margin-top: 100px;">
  <tr>
    <td>
      <div style="margin-top: 50px;background-color:blue; height:100px;">

        <div id="id" style="background-color: red; width: 20px; height:20px;">
        </div>
      </div>
    </td>
  </tr>
</table>

这是因为 div 的父元素是 table 对象,而 div 的顶部到其父元素的距离为 51px。

查看此页面以更深入地讨论 offsetTop (https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop)

而此页为 offsetParent (https://developer.mozilla.org/en-US/docs/Web/API/HTMLelement/offsetParent)