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

后端 未结 12 1111
你的背包
你的背包 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:37

    jQuery implements this quite elegantly. If you look at the source for jQuery's offset, you'll find this is basically how it's implemented:

    var rect = elem.getBoundingClientRect();
    var win = elem.ownerDocument.defaultView;
    
    return {
        top: rect.top + win.pageYOffset,
        left: rect.left + win.pageXOffset
    };
    

提交回复
热议问题