如果用户一直向下滚动,则按间隔向下滚动

Scrolling down on interval if the user is scrolled all the way down

本文关键字:滚动 用户 如果 一直      更新时间:2023-09-26

我有这个问题,

我正在创建一个聊天,每2秒更新一次,通过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语句应该阻止它…对吧?

我建议这样设置一个标志:

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

这样当用户向上滚动时,标志为假,当用户向下滚动时,标志为真。