【发布时间】:2015-07-19 18:05:27
【问题描述】:
您好,我正在编写一个聊天网站,但包含消息的 div 有问题。在 CSS 中,包含消息的 div 具有 overflow: auto; 以允许滚动条。现在的问题是,当 ajax 通过从数据库中获取消息的 PHP 脚本获取消息时,您无法向上滚动。 AJAX refreshMessages() 函数设置为使用window.setInterval(refreshMessages(), 1000); 每秒更新一次。这是我想要的,但是当我向上滚动查看以前的消息时,由于 AJAX 获取功能,滚动条会直接回到聊天结束。
对问题所在有什么想法吗?
AJAX 代码:
//Fetch All Messages
var refreshMessages = function() {
$.ajax({
url: 'includes/messages.inc.php',
type: 'GET',
dataType: 'html'
})
.done(function( data ) {
$('#messages').html( data );
$('#messages').stop().animate({
scrollTop: $("#messages")[0].scrollHeight
}, 800);
})
.fail(function() {
$('#messages').prepend('Error retrieving new messages..');
});
}
编辑:
我正在使用此代码,但它不能正常工作,它会暂停功能,但当滚动条回到底部时,功能不会重新启动。帮忙?
//Check If Last Message Is In Focus
var restarted = 0;
var checkFocus = function() {
var container = $('.messages');
var height = container.height();
var scrollHeight = container[0].scrollHeight;
var st = container.scrollTop();
var sum = scrollHeight - height - 32;
if(st >= sum) {
console.log('focused'); //Testing Purposes
if(restarted = 0) {
window.setTimeout(refreshMessages(), 2000);
restarted = 1;
}
} else {
window.clearInterval(refreshMessages());
restarted = 0;
}
}
【问题讨论】:
-
您是否在动画前使用
.stop()取消任何先前的动画?