gpt4 book ai didi

jquery - 在将项目添加到列表时保持窗口不改变滚动位置?

转载 作者:行者123 更新时间:2023-12-03 21:29:21 25 4
gpt4 key购买 nike

我有一个显示消息的页面,我希望它像 Facebook 一样工作,但没有惰性加载程序。消息按时间顺序显示,最近的在最后。

我的消息列表最初填充了 x 条最新消息,并且窗口滚动到底部。当用户开始阅读线程时,他们会从下到上阅读。如果他们到达顶部,他们可以加载更多消息...我让他们单击一个按钮...facebook 有一个惰性加载程序。新消息将添加到列表前面。

问题:当新消息被添加到前面时,现有消息被下推,导致用户失去他们的“查看”位置。添加新消息时如何保持用户当前的 View 位置?例如,在 facebook 中打开一条长消息线程,滚动到顶部导致添加新消息...即使滚动位置发生变化,您的 View 位置也不会改变。

最佳答案

在添加新消息之前存储对第一条消息的引用,在添加新消息之后,将滚动设置为该消息的偏移量:

$(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/

关于jquery - 在将项目添加到列表时保持窗口不改变滚动位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9834143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com