Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am wondering how I can get the number of pixels (or measurement in general) from a div to the top of the window in Javascript. I am not looking for an offset y in relation to the document, simply to the top of where the browser is displaying. I tried the "answered" solution here: Is it possible to get the position of div within the browser viewport? Not within the document. Within the window, but at least in Safari, I am running into a problem where it returns the same number no matter where the div's really are.

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
223 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

From this 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
var top = viewportOffset.top;
var left = viewportOffset.left;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...