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

What's the proper way to get the position of an element on the page relative to the viewport (rather than the document). jQuery.offset function seemed promising:

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

But that's relative to the document. Is there an equivalent method that returns offsets relative to the viewport?

See Question&Answers more detail:os

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

1 Answer

The easiest way to determine the size and position of an element is to call its getBoundingClientRect() method. This method returns element positions in viewport coordinates. It expects no arguments and returns an object with properties left, right, top, and bottom. The left and top properties give the X and Y coordinates of the upper-left corner of the element and the right and bottom properties give the coordinates of the lower-right corner.

element.getBoundingClientRect(); // Get position in viewport coordinates

Supported everywhere.


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