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;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…