商店,你在前面加上新的消息之前,你在前面加上后,设置滚动到该消息的偏移的第一条消息的引用:
$(document).on('scroll', function() {
var scroll = $(document).scrollTop();
if (scroll < 1) {
// Store eference to first message
var firstMsg = $('.message:first');
// Prepend new message here (I'm just cloning...)
$('body').prepend(firstMsg.clone());
// After adding new message(s), set scroll to position of
// what was the first message
$(document).scrollTop(firstMsg.offset().top);
}
});
演示:http://jsfiddle.net/GRnQY/
编辑:我注意到你想用一个按钮。您可能需要做一些更多的数学:
$(document).on('click', '#loadMore', function() {
var firstMsg = $('.message:first');
// Where the page is currently:
var curOffset = firstMsg.offset().top - $(document).scrollTop();
// Prepend
firstMsg.before(firstMsg.clone());
// Offset to previous first message minus original offset/scroll
$(document).scrollTop(firstMsg.offset().top-curOffset);
});
演示:http://jsfiddle.net/GRnQY/5/
第二种解决方案非常棒 - 非常感谢您,这对于实现Facebook反向信息的“反向无限滚动”非常有帮助。 – 2012-10-22 19:48:44
如果您使用的是ajax,请在滚动的ajax'success'属性上添加'$(selector).scrollTop(firstMsg.offset()。top-curOffset);'以便正常工作 – user3284463 2015-11-27 18:02:58
太棒了!谢谢杰夫! – Can 2016-01-07 08:05:19