Why is position().top changing when I scroll the p

2019-08-04 04:27发布

jQuery position() returns

the current coordinates of the first element in the set of matched elements, relative to the offset parent.

So, scrolling the parent is not supposed to change the position, right?

The result I'm getting in this fiddle is that after scrolling the parent by 100px, the position().top of a child element changes by 100.

position().top before scroll 1880, after scroll 1780

Why?

1条回答
地球回转人心会变
2楼-- · 2019-08-04 04:45

To answer the question in your comments, just add the box's scrollTop to the anchored element's position.

http://jsfiddle.net/5xqEL/17/

var $box = $('#box'),
    $anchored = $('#anchored'),
    $debug = $('#debug');

$debug.text('position().top before scroll ' + ($anchored.position().top + $box.scrollTop()));

$box.animate({
    scrollTop: 100
}).promise().then(function () {
    $debug.text($debug.text() + ', after scroll ' + ($anchored.position().top + $box.scrollTop()));
});
查看更多
登录 后发表回答