我需要一些使用示例来了解如何实现此目的。我有一些 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/举个实际例子。