文档就绪时,jQuery AUTOMATIC滚动(无按钮单击)

时间:2015-12-22 15:31:46

标签: javascript jquery scroll chat

我正在创建一个聊天,一切都很完美,当我点击"发送"按钮,但我希​​望它在文档准备好时一直向下滚动。我通过向setInterval添加滚动功能来完成此操作,但问题是用户基本上无法向上滚动以查看以前的聊天消息,因为他每0.1秒向下滚动一次。我的代码是:

    $(function () {

        //$("#messages").scrollTop($("#messages").prop("scrollHeight")); Doesnt work at all

        function updateChat(){
            $("#messages").load('chat/ajaxLoad.php');
            //$("#messages").scrollTop($("#messages").prop("scrollHeight")); This works but the user cannot scroll up anymore
        }

        setInterval(function () {
            updateChat();
        }, 100);


        $("#post").submit(function(){
            $.post("chat/ajaxPost.php", $('#post').serialize(), function (data) {
                $("#messages").append('<div>'+data+'</div>');
                $("#messages").scrollTop($("#messages").prop("scrollHeight")); // This works but only when the user presses the send button
                $("#text").val("");
            });
            return false;
        });
    });

3 个答案:

答案 0 :(得分:1)

将此添加到您的代码中。

var chat = $("#messages").html();
setInterval(function () {
    updateChat();
    if(chat !== $("#messages").html()){
        $("#messages").scrollTop($("#messages").prop("scrollHeight"));
        chat = $("#messages").html();
    }
}, 2000);

我认为这应该有效(没有测试),但是有一些更好的方法可以优化它,就像不将整个.html()保存到变量中一样。

这里的想法是检查内容是否每2秒更改一次。如果是,则向下滚动。

答案 1 :(得分:0)

我知道你的问题是什么,我有2个想法:

  1. 只有在发布新消息时向下滚动,例如,使用Ajax请求,您可以检查消息的数量是否为&gt;与过去0.1s相比,如果是,则滚动,如果不是,则忽略。
  2. 如果滚动位于最大底部位置,则每1-2秒仅向下滚动。如果滚动不是最大值,则不滚动。我觉得这个解决方案更好。

答案 2 :(得分:0)

您需要在应用程序上分离操作, 你也错过了许多可以使应用程序正常运行的检查 让它易于维护。

我建议代码看起来如何:

$(function () {

    function updateMessages(){
        var messages_before_update = $("#messages").html();
        $("#messages").load('chat/ajaxLoad.php');
        var message_after_update = $("#messages").html();
        if(messages_before_update !== message_after_update){
            scrollToBottom();
        }

    }

    function scrollToBottom(){
        var scroll_height = $("#messages").prop("scrollHeight");
        var scroll_top = $("#messages").scrollTop();
        if(scroll_height !== scroll_top){
            $("#messages").scrollTop($("#messages").prop("scrollHeight"));
        }
    }

    function addMessage(message){
        $("#messages").append('<div>' + message + '</div>');
    }

    setInterval(updateMessages, 100);

    $("#post").submit(function () {
        $.post("chat/ajaxPost.php", $('#post').serialize(), function (data) {
            addMessage(data);
            scrollToBottom();
            $("#text").val("");
        });
        return false;
    });
});