javascript - 如何正确获取 DOM 元素的位置偏移量?

标签 javascript html

我正在尝试使用 element.getBoundingClientRect() 查找元素的偏移量,但是这样做的问题是,如果网页的高度很长并且涉及滚动,则该函数会返回元素的偏移量 window 。如何获取页面顶部的偏移量?

最佳答案

documentation for getBoundingClientRect()通过一个简短的示例涵盖您的用例:

The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle. This means that the rectangle's boundary edges (top, left, bottom, and right) change their values every time the scrolling position changes (because their values are relative to the viewport and not absolute). If you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the top and left properties (these can be obtained using window.scrollX and window.scrollY) to get a bounding rectangle which is independent from the current scrolling position.

关于javascript - 如何正确获取 DOM 元素的位置偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39444269/

相关文章:

javascript - React.js 阻塞 header

javascript - 从一副牌中发牌和从阵列中取出牌

javascript - 如何使用 a-Frame VR 网站隐藏或显示元素

javascript - 以特定大小在 div 中放映幻灯片

javascript - 如何旋转和镜像 Canvas 元素?

javascript - WebKit 中有类似 canvas.drawWindow() 的东西吗?

javascript - Angular 7 - 只有 "dist"文件夹在浏览器上渲染,但使用 NodeJS 则不渲染 "src"文件夹

php - 在 php 代码中使用 JS 变量?

html - 如何将当前内容放入有边距的面板中?

javascript - 如何使用 jQuery 从 onchange 中选择输入值?