反向无限滚动

3

我想制作一个即时通讯应用,消息显示方式类似于聊天,底部到顶部滚动。当滑动到顶部时,系统会加载更多的消息。

问题在于加载新项目后控制 scrollTop 的位置。如何计算这个位置?

  • 给出了 Meteor 的示例,但纯 JS(理论)的答案也会有帮助

HTML

<template name='chatBox'>
    <div class='chat-box'><!--viewport-->

        {{> chatBoxItem}}
        {{/each}}
    </div>
</template>

<template name='chatBoxItem'>
    <div class='chat-box-wrapper'><!--content block-->
        {{#each messeges}}
            <p>{{messege}}</p> <!--each messege-->
        {{/each}}
    </div>
</template>

JS

Template.chatBox.onRendered(function() {
    // viewport template

    $('.chat-box').scroll(function(e) {
        var chatBoxHeight = $('.chat-box').innerHeight(); 
        var wrapperHeight = $('#chat-box-wrapper').innerHeight();
        var chatBoxScroll = $('.chat-box').scrollTop();

        var currentScrollFromBottom = wrapperHeight - chatBoxScroll; //don't sure if this formula is correct but it's count how many pixels was scrolled from bottom to top

        if (currentScrollFromBottom  == wrapperHeight && MESSAGES_LIMIT < amountOfMessages) {

            //here some code to increase limit of queue

        }
    });


Template.chatBoxItem.onRendered(function () {
    // content template

    var $heightOfBlock = $('#chat-box-wrapper').height();
    $('.chat-box').scrollTop($heightOfBlock); 
    // Here I have the most problem, 
    // I need to scroll to bottom when page is load (work good)                     
    // but after loaded new items, it's need to stand still, but   
    // it's not. I don't know which formula i need     
    // to use to count current scroll position 

});

也许这个例子完全错误,但我不明白如何使无限滚动从底部向上。

更新:

我找到了这个公式,但它是用于正常滚动的,我需要如何重建这个以适应反向滚动?

$(window).scrollTop() + $(window).height() > $(document).height() - 100
1个回答

1

我用jQuery解决了这个问题:

var st=$("#chat").scrollTop();
$("#chat").prepend(me);
$("#chat").scrollTop(st+me.outerHeight());

https://jsfiddle.net/Lhmn07rg/8/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接