JavaScript getBoundingClientRect() changes while scrolling

前端 未结 2 1360
攒了一身酷
攒了一身酷 2020-12-04 08:42

I want to have the exact distance between the Y-coordinate of an element an the Y-value=0, which I consider as the top of the document.

myElement.getBounding         


        
2条回答
  •  孤街浪徒
    2020-12-04 09:16

    It is because getBoundingClientRect() gets values with respect to the window(only the current visible portion of the page), not the document(whole page).
    Hence, it also takes scrolling into account when calculating its values
    Basically, document = window + scroll

    So, to get the distance between myElement and the Y-coordinate=0 (top of document), you would have add the value of vertical-scroll also:

    myElement.getBoundingClientRect().top + window.scrollY;

    Source: https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect

提交回复
热议问题