问题
I have a div with position "fixed" and I want to get the value of its position relative to the whole document while the user scrolls down the page.
So, lets say I place the div on (x=0,y=0) and then the user scrolls down a bit and now, relative to the document, the div is on (X=0,y=300). I want to get that information, I want to know the exact position of that div in every moment, again, relative to the whole document, not to the window or the browser.
I've tried many things but nothing seems to get what I'm trying to.
One of them is this code, which does not work in the case of a fixed div:
var position = $("#fixed").offset(); /*it gets the position of the div
"fixed" relative to the document*/
$("#fixed").html(position.top); /*it prints the obtained
value on the div "fixed"*/
Here you can find the running code, and you can see that, when you scroll down, the value of the position of the div does not change.
If I am not wrong, the code should print a new value on the div everytime it changes its vertical position relative to the document. But it turns out that it does not happen.
SOLVED:
The question was solved by codef0rmer. I was missing to track the scrolling to refresh the value of the position of the fixed div. I was an idiot. So the final code works fine the way he wrote it:
$(function () {
var position = $("#fixed").offset();
$("#fixed").html(position.top);
$(window).scroll(function () {
var position = $("#fixed").offset();
$("#fixed").html(position.top);
});
})
And here you can see the running code.
Thank you everyone and specially to codef0rmer.
回答1:
you can use .offset() to get the current coordinates of the element relative to the document whereas .position() to get the current coordinates of an element relative to its offset parent.
回答2:
.offset() gives you the coordinates relative to the whole document.
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.
.offset() returns an object containing the properties top and left.
Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.
回答3:
Unless you refresh the page and the scrollbar is at a different position at the moment it initialize.
来源:https://stackoverflow.com/questions/9527783/get-the-position-of-a-fixed-div-with-jquery