jQuery-在将项目放在列表前面时,保持窗口不更改滚动位置? [英] jquery - keep window from changing scroll position while prepending items to a list?

查看:138
本文介绍了jQuery-在将项目放在列表前面时,保持窗口不更改滚动位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a page that displays messages and I want it to work just like Facebook, but without the lazy loader. Messages are displayed in chronological order, most recent last.

最初,我的消息列表是x最新消息的数量,并且窗口滚动到底部.当用户开始阅读线程时,他们从下至上阅读.如果他们到达顶部,他们可以加载更多消息...我让他们单击一个按钮... facebook有一个懒惰的加载器.新消息将添加到列表中.

My message list is initially populated x number of most recent messages, and the window is scrolled to the bottom. When the user starts to read the thread, they read from bottom to top. If they get to the top, they can load more messages... I make them click a button... facebook has a lazy loader. New messages are prepended to the list.

问题:在添加新消息时,现有消息被下推,导致用户失去其查看"位置.添加新消息时,如何保持用户当前的视图位置?例如,在Facebook中打开一个长消息线程,滚动到顶部,导致添加新消息...即使滚动位置发生变化,您的视图位置也不会改变.

Problem: As the new messages are prepended, the existing messages are pushed down, causing the user to lose their "viewing" place. How can I keep the user's current view position as I add the new messages? For an example, open a long message thread in facebook, scroll to the top causing new messages to be added... your view location doesn't change even though the scroll position does.

推荐答案

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

Store a reference to the first message before you prepend new messages, and after you prepend, set the scroll to the offset of that message:

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

编辑:我注意到您需要一个按钮.您可能需要做更多的数学运算:

Edit: I noticed you wanted it with a button. You might have to do a little more math:

$(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-在将项目放在列表前面时,保持窗口不更改滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆