Pregunta

I am using the $.position over the same selector and I am getting different results for the top value.

The problem might be in getting the position of the selector inside the scrolling div. That's why I am using $.position instead of $.offset, but it seems I am doing something wrong.

You can try it clicking multiple times on the the text "Get Position" at my fiddle: http://jsfiddle.net/FgftM/1/

Once the div has scrolled to look for the selector, clicking on the "Get Position" again shouldn't do anything because I am already on the selector position.

The resulting position values showed at the bottom.

To clarify the structure of the page, here's an sketch: enter image description here

Original fiddle: http://jsfiddle.net/BtZQE/16/

¿Fue útil?

Solución

I believe what you want to do is set position: relative on #content. That way the position is calculated in relation to the container instead of the overall page.

http://jsfiddle.net/FgftM/6/

EDIT: After some clarification, you still need the position: relative but you also need to add in the current scrollTop value:

http://jsfiddle.net/FgftM/8/

var top = dest.top + $('#content').scrollTop();

Otros consejos

@James has a correct solution, but to provide additional clarification: position is relative to the offsetParent, which is not necessarily the element's immediate ancestor.

For the algorithm used to determine an element's offsetParent, see http://www.w3.org/TR/cssom-view/#offset-attributes

The relevant point here, as James pointed out, is that the offsetParent's position property must be something other than static, and if there is no such ancestor, the offsetParent will be the body element

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top