Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

javascript - Position of Div in relation to the Top of the Viewport

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!

question from:https://stackoverflow.com/questions/1960082/position-of-div-in-relation-to-the-top-of-the-viewport

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

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...