我想知道如何在 Javascript 中获取从 div 到窗口顶部的像素数(或一般测量值)。我不是在寻找与文档相关的偏移量 y,只是在浏览器显示位置的顶部。我在这里尝试了“已回答”的解决方案:Is it possible to get the position of div within the browser viewport? Not within the document. Within the window ,但至少在 Safari 中,我遇到了一个问题,无论 div 的实际位置如何,它都会返回相同的数字。
感谢您的帮助!
最佳答案
现有答案现已过时。 getBoundingClientRect()
方法已经存在了很长一段时间,并且完全满足了这个问题的要求。此外,所有浏览器都支持它。
来自 this MDN 页面:
返回值是一个 TextRectangle 对象,它包含描述边框的只读左、上、右和下属性,以像素为单位,左上相对于左上视口(viewport)的。
你可以这样使用它:
var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport
var top = viewportOffset.top;
var left = viewportOffset.left;
关于javascript - Div 相对于视口(viewport)顶部的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1960082/