【问题标题】:Checking whether the user is scrolling or not and if not then set scroll position to bottom检查用户是否正在滚动,如果没有,则将滚动位置设置为底部
【发布时间】:2016-12-05 21:19:19
【问题描述】:

目前我正在开发一个聊天网站。聊天框每 200 毫秒更新一次。加载新消息时,滚动条需要位于底部。我已经做到了。问题是,当用户尝试滚动到顶部位置时,滚动条每 200 毫秒落到底部(因为我已设置每 200 毫秒加载新消息并将滚动条重新定位到底部。)。所以这就是问题所在。现在我想检查用户是否正在滚动或已经滚动。如果在 count 开始播放时用户已经滚动或滚动,则滚动条将保持在原处。如果用户根本没有滚动,现在也没有滚动,那么每次有新消息到达时,滚动条都会转到底部位置...

这是我的代码。

   <div class="scrollbar" id="style-2" id="scrollBar">
       <div id="conversation">
       </div>                 
    </div>

<script>
 function loadConversation(){
    $.get("get-conversation.php?to_hash=00000", function(data, status){
    document.getElementById("conversation").innerHTML = data;

    ///Scrolling to bottom
    var container_height = $( "#contain" ).height();
    $( "div.scrollbar" ).scrollTop( container_height+1000000000000 );


});

setTimeout(loadConversation,200);       
}
loadConversation();`

请帮帮我。这对我来说非常重要……我将不胜感激。

【问题讨论】:

    标签: javascript jquery scroll scrollbar


    【解决方案1】:

    这有点粗糙。它使计时器继续运行,但仅在用户滚动时停止滚动到底部,并在用户停止滚动时继续。

    var isScrolling = false;
    
    $(window).scroll(function() {
        isUserScrolling = true;
        clearTimeout($.data(this, 'scrollTimer'));
        $.data(this, 'scrollTimer', setTimeout(function() {
            // do something
            isUserScrolling = false;
        }, 250));
    });
    
     function loadConversation(){
         if(!isUserScrolling){
            $.get("get-conversation.php?to_hash=00000", function(data, status){
               document.getElementById("conversation").innerHTML = data;
    
               ///Scrolling to bottom
               var container_height = $( "#contain" ).height();
                $( "div.scrollbar" ).scrollTop( container_height+1000000000000 );
    
    
           });
        }
        setTimeout(loadConversation,200);       
    }
    loadConversation();`
    

    【讨论】:

    • 我不知道你的代码。这是概念性的。您将不得不尝试这个想法并在每个步骤中记录控制台日志。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 2016-11-03
    • 2018-03-04
    • 2018-08-06
    • 2011-11-28
    • 2021-09-02
    相关资源
    最近更新 更多