Jquery get element top position relative to window năm 2024

jQuery's .offset[] method is pretty close to what we want, except it gets the offset coordinates for an object in relation to the whole document. What we'd want is to couple this with the .scrollTop[] and .scrollLeft[] methods.

.scrollTop[] will give you the number of pixels scrolled from the top of an object, so you basically want to take the difference of the scrollTop of the document and the actual offset top coordinate to get the viewport top offset.

coffeescript example:

photo = $['
# photo']
offset = photo.offset[]
photoViewportOffsetTop = offset.top - $[document].scrollTop[]
photoViewportOffsetLeft = offset.left - $[document].scrollLeft[]

$[document].scrollTop[]

Make sure you use $[document] as the object you're looking for the scrollTop[] or scrollLeft[] for, rather than the object itself, because the object might not be scrolled out of the frame. You want the offset of the viewport scrolled away from the document.

In order to get the location of an element relative to the document, jQuery offset[] method is used. The offset[] method is an inbuilt method in jQuery which is used to set or returns the offset coordinates of the selected element. We can also use the jQuery position[] method. The position[] method is an inbuilt method in jQuery which is used to find the position of the first matched element relative to its parent element in the DOM tree. Syntax:

$[selector].offset[]

Below examples illustrate the above approach: Example 1:

`

`2 `3

`2 `5

`2 `7

`9 0> `

`4

`9`head`5> `

`1 2> 1> `

`

`1 2> 1> `

`

`

`4> `

`2 `27

`

`9 `

`9`html >

Output:

Example 2:

`

`2 `3

`2 `64

`2 `7

`9 0> `

`4

`9`head`5> `

`1 2> 1> `

`

`1 2> 1> `

`

`

`4> `

`2 `27

Chủ Đề