【发布时间】:2011-05-19 10:56:04
【问题描述】:
我需要一些使用示例来说明如何实现这一点。我有一些 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 插件,但只是需要一些例子。
提前致谢!
编辑:这是为感兴趣的人提供的解决方案。
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);
}
转到http://www.jsfiddle.net/f4YFL/4/ 以获取此操作的示例。
【问题讨论】:
-
Ty,对于这篇文章。但是,给定的解决方案对我不起作用。也许是因为,我使用
html标签作为elem。但是,找到了解决方法:var atBottom = ($(window).height() + elem.scrollTop() == elem.outerHeight());。也许有人需要它:)
标签: html ajax jquery-plugins jquery