商店,你在前面加上新的消息之前,你在前面加上後,設置滾動到該消息的偏移的第一條消息的引用:
$(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