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

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

    The existing answers are now outdated. The native getBoundingClientRect() method has been around for quite a while now, and does exactly what the question asks for. Plus it is supported across all browsers (including IE 5, it seems!)

    From MDN page:

    The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

    You use it like so:

    var viewportOffset = el.getBoundingClientRect();
    // these are relative to the viewport, i.e. the window
    var top = viewportOffset.top;
    var left = viewportOffset.left;
    

提交回复
热议问题