javascript - Div 相对于视口(viewport)顶部的位置

标签 javascript html browser pixel

我想知道如何在 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/

相关文章:

javascript - 修改嵌套对象,然后返回修改后的父对象

javascript - jQuery 在切换期间更改 'a' 标签的属性

java - 网上冲浪/浏览器自动化

google-chrome - 如何强制在 Chrome 中打开链接而不下载它们?

html - div 底部带有渐变的 CSS 三 Angular 形

javascript - html5 canvas在firefox下性能不佳

javascript - 从 javascript 访问模型属性

javascript - 为什么修改 Number.prototype.toString 不起作用?

javascript - 如何使用 create-react-app 创建新项目

javascript - HTML/CSS/JavaScript : Force child elements to never exceed parent size without modifying children