Jquery聊天框滚动问题

时间:2015-05-23 18:02:43

标签: jquery

我正在创建一个聊天框。当用户键入msg时,它会立即显示在聊天框中。滚动条应始终滚动到聊天框的底部。以下代码确实有效,但是当我尝试将条形图滚动到顶部以查看上一个消息时,它将始终被拖回到底部。我不确定是因为setInterval。知道如何解决这个问题吗?

$(function(){
     $("#textmsg").keypress(function (e) {
        if (((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) && !e.shiftKey){
            $('.post').click();
            return false;
        } else {
            return true;
        }
    });


    $(document).on('submit','#discussionForm',function(){
        var textmsg = $.trim($("#textmsg").val());
        var name = $.trim($("#name").val());
        if(textmsg != "" && name!=""){
                $.post('inc/postMessages.php',  $("#discussionForm").serialize(), function(data){
                    $(".discussionMessages").html(data);
                });
                $("#textmsg").val('');
        }else{
            alert("Please enter some text!");
        }
    });

    setInterval(function(){
        getMessages();
    },800);
});

function getMessages(){
    $.get('inc/getMessages.php', function(data){
    var message = $(".discussionMessages");
    message.html(data);
    message.scrollTop(message[0].scrollHeight);
    });
}

我已查看过这篇文章AJAX Chat Box Scrolling Up Issue,但我不确定如何申请我的代码。

1 个答案:

答案 0 :(得分:1)

每800毫秒加载整个会话是非常低效的 - 您应该确定每次加载时只提取新消息,甚至更好地切换到websockets或类似内容。但是我不知道你的用例,我不会详细说明,因为这不是你要问的问题。

所以回答你的问题:你需要做的只是在发布新内容时滚动,所以只需跟踪并比较以前的内容和新内容,只做东西 - 包括滚动,如果他们不是等于:

var old_content = '';
function getMessages(){
    $.get('inc/getMessages.php', function(data){
        if (data !== old_content) {
            var message = $(".discussionMessages");
            message.html(data);
            message.scrollTop(message[0].scrollHeight);
            old_content = data;
        }
    });
}

如果您不希望它滚动,即使用户滚动离开底部时收到新消息,您也可以添加一个检查:

var old_content = '';
function getMessages(){
    $.get('inc/getMessages.php', function(data){
        if (data !== old_content) {
            var message = $(".discussionMessages");
            /* scrollTop gives the position from the top, while
             * scrollheight gives the entire content height - so
             * we need to add the innerHeight (ie. height of the
             * scrollable element) to get the bottom of the current
             * view - you actually ought to subtract the innerHeight
             * from the scroll function itself too, it just doesn't
             * matter as long as the value you pass is larger than
             * the scrollHeight it will hit the bottom...
             */
            var do_scroll = (message.scrollTop() + message.innerHeight() >= message[0].scrollHeight);
            message.html(data);
            if (do_scroll) message.scrollTop(message[0].scrollHeight);
            old_content = data;
        }
    });
}