How to get an element's top position relative to the browser's viewport?

后端 未结 12 1199
你的背包
你的背包 2020-11-29 17:17

I want to get the position of an element relative to the browser\'s viewport (the viewport in which the page is displayed, not the whole page). How can this be done in JavaS

12条回答
  •  心在旅途
    2020-11-29 17:51

    On my case, just to be safe regarding scrolling, I added the window.scroll to the equation:

    var element = document.getElementById('myElement');
    var topPos = element.getBoundingClientRect().top + window.scrollY;
    var leftPos = element.getBoundingClientRect().left + window.scrollX;
    

    That allows me to get the real relative position of element on document, even if it has been scrolled.

提交回复
热议问题