Offset (). top doesn't work as expected if parent is patched

I am using a position : fixed

div for the stick which is at the top of the page, but when I use offset().top

for its child value it gives different values ​​when scrolling. i tried like:

CSS:

.parent{
    position : fixed;
    top : 0px;
}
.child{
    height : 20px;
    margin-top : 10px;
}

      

JS:

console.log($(".child").offset().top);

      

the above JS code gives different results when scrolling the page.

+3


source to share


4 answers


Use .position () to get the current coordinates of an element relative to its offset parent. The .offset () method gives you coordinates relative to the entire document.



$(".child").position()

      

+5


source


As you can read it here: http://api.jquery.com/offset/

Get the current coordinates of the first item, or set the coordinates of each item in the set of matched items, relative to the document.

Bias(). top gives pixels from the element at the top of the page.



Maybe you should use .position (). top quote from http://api.jquery.com/offset/

Contrast this with .position (), which retrieves the current position relative to the offset parent.

0


source


You can use jquery position.top

to get the top position for the div http://api.jquery.com/position/

0


source


You can check the link below. There is an explanation on how to calculate the top position given scrollTop. fooobar.com/questions/18797 / ...

0


source







All Articles