2015-10-09 104 views
1

我有这个问题,向下滚动区间,如果用户向下滚动

我创建一个聊天,其中更新每隔2个secounds一路,通过AJAX。

现在我想滚动到底部,每次加载时,都很有效。

现在的问题是,如果他们向上滚动检查旧消息,它会向下滚动,烦人的权利?现在我试着想出一个解决方案,这应该是工作。但我很愚蠢。任何人都可以帮助我吗?:

function loadChat() { 
    $.ajax({ 
     url: 'ajax/load_chat.php', 
     success: function(data) { 
      $('#chatbox').html(data); 
      //console.log($('#chatbox')[0].scrollHeight - $('#chatbox').innerHeight()); 
      //console.log($('#chatbox').scrollTop()); 
      if($('#chatbox')[0].scrollHeight - $('#chatbox').innerHeight() + 50 < $('#chatbox').scrollTop()) { 
       $("#chatbox").stop().animate({ scrollTop: $('#chatbox')[0].scrollHeight}, 200); 
      } 
     }, 
    }); 
} 

这段代码让它向下滚动,不管是什么,但我的if语句应该停止那个......对吧?

+0

感谢taxicala为编辑:)我不知道为什么它没有缩进编号:S – Dyrhoi

回答

1

我建议设置一个标志如下:

var atBottom = true; 
$('#chatbox').on('scroll', function() { 
    if($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight) { 
     atBottom = true; 
    } else { 
     atBottom = false; 
    } 
}); 

function loadChat() { 
    $.ajax({ 
     url: 'ajax/load_chat.php', 
     success: function(data) { 
      $('#chatbox').html(data); 
      //console.log($('#chatbox')[0].scrollHeight - $('#chatbox').innerHeight()); 
      //console.log($('#chatbox').scrollTop()); 
      if(atBottom) { 
       $("#chatbox").stop().animate({ scrollTop: $('#chatbox')[0].scrollHeight}, 200); 
      } 
     }, 
    }); 
} 

当用户滚动起来,则标记被falsy当用户滚动至底部,它得到truthy这样。

+0

它的工作原理现在我把我的