gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:32:23 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com