jquery - keep window from changing scroll position while prepending items to a list?

前端 未结 6 945
误落风尘
误落风尘 2020-11-29 23:10

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.<

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 23:37

    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);
        }
    });
    

    Demo: 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);
    });
    

    Demo: http://jsfiddle.net/GRnQY/5/

提交回复
热议问题