创建具有高级滚动功能的 AJAX 聊天。如何?

2023-12-30

我需要一些使用示例来了解如何实现此目的。我有一些 HTML:

<div id="chatDisplay">
</div>
<input type="text" id="message" /><input type="button" id="send" value="Send" />

然后我有一些 JQuery:

// This function sets up the ajax that posts chat messages to the server.
$(function()
{
     $('#send').click(function ()
     {
          $.ajax(
          {
               url: "chat/postmsg",,
               data: { msg: $('#message').val(); },
               type: "POST",
               success: function (response)
               {
                    // Server sends back formated html to append to chatDisplay.
                    $('#chatDisplay').append(response);
                    //scroll to bottom of chatDisplay
               }
          });
     });
});

// This function periodically checks the server for updates to the chat.
$(function ()
{
     setInterval(function()
     {
          $.ajax(
          {
               url: "chat/getupdates",
               type: "POST",
               success: function (response)
               {
                         // Server sends back any new updates since last check.
                         // Perform scroll and data display functions. Pseudo-code to follow:

                         // If (chatDisplay is scrolled to bottom)
                         // {
                         //     append response to chatDisplay
                         //     scroll to bottom of chatDisplay
                         // }
                         // else if (chatDisplay is scrolled up from bottom by any amount)
                         // {
                         //     append response to chatDisplay, but do not scroll to bottom.
                         // }
               }
          });
     }, 7000);
});

这只是基本聊天功能的示例,当然不包括服务器端代码。我需要的是如何完成伪代码所描述的内容的使用示例。如何检测用户是否滚动到 DIV 底部,以及如何将它们滚动到底部?如果他们向上滚动查看聊天记录,我不希望他们跳到 DIV 的底部。

我听说过 JQuery 的 ScrollTo 插件,但只需要一些例子。

提前致谢!

EDIT:这是感兴趣的人的解决方案。

success: function (response)
{
     var elem = $('#chatDisplay');
     var atBottom = (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight());
     $('#chatDisplay').append(response);
     if (atBottom)
          $('#chatDisplay').scrollTop($('#chatDisplay')[0].scrollHeight);
}

Go to http://www.jsfiddle.net/f4YFL/4/ http://www.jsfiddle.net/f4YFL/4/举个实际例子。


似乎您可以将伪代码重构为:

将响应附加到 chatDisplay if(聊天显示在底部){ 滚动到底部 }

以下是如何确定是否滚动到底部的链接:

http://yelotofu.com/2008/10/jquery-how-to-tell-if-youre-scroll-to-bottom/ http://yelotofu.com/2008/10/jquery-how-to-tell-if-youre-scroll-to-bottom/

希望有帮助。

Bob

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建具有高级滚动功能的 AJAX 聊天。如何? 的相关文章

随机推荐