【发布时间】:2019-02-24 16:44:31
【问题描述】:
我正在构建一个信使网站,并希望在刷新页面时聊天自动滚动到聊天提要的底部(最新消息)。我对 jQuery 很陌生,经过一番搜索后,我已经使用 animate() 让它工作了。例如,当页面在表单提交后重新加载时首次加载太不和谐时,这非常有用。
有没有什么方法可以自动滚动到容器的底部而不给它设置动画?
// When page loads
$(document).ready(function(){
// Load chat. ALSO the chat has to be hard coded in here.
$('#MessagesContainer').load('/php/chat_ref.php');
// Scroll to the bottom of the page. ALSO ".height()+500" was a bit of a bodge.
$("#MessagesContainer").animate({ scrollTop:$('#MessagesContainer').height()+500}, 100);
return false;
});
// Every 2 seconds.
var auto_refresh = setInterval(function(){
// Reload the chat.
$('#MessagesContainer').load('/php/chat_ref.php');
return false;
}, 2000);
【问题讨论】:
-
是的,只需手动设置
scrollTop():$("#MessagesContainer").scrollTop($('#MessagesContainer').height()+500);。但是您应该注意,AJAX 轮询是一个非常糟糕的主意,因为它根本不能很好地扩展。要构建聊天系统,您应该使用 Websockets 或服务器发送的事件。
标签: javascript jquery html scrolltop