我正在使用php和jQUERY创建一种消息系统,当你点击用户个人资料并点击消息按钮它将我们带到消息页面时,加载上一条消息大约需要2秒,所以我添加了一个代码加载ajax后滚动到包含所有消息项的div类的底部,以显示最新消息,但我遇到的问题是当我尝试向上滚动时我遇到问题,我尝试向上滚动的那一刻我添加的代码单独下载,任何解决方案都将受到赞赏。
这是我的JQ代码 - 如果还有其他任何东西可以帮助我解决这个问题,我会尽快完成。
$(document).ready(function(){
/*post message via ajax*/
//get message
var c_id = $("#conversation_id").val();
//get new message every 2 second
setInterval(function(){
$(".display-message").load("get-message-ajax.php?c_id="+c_id , stateChange);
}, 2000);
});
function stateChange() {
var newstate = true;
if(newstate = true){
$(".conversation_history.clearfix").animate({
scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight
}, 1000)} else {
$(".conversation_history.clearfix").end();
var newstate = false;
}
}
来自get_message-ajax.php的代码
<?php
include 'db.php';
include 'function.php';
/*Get Message*/
if(isset($_GET['c_id'])){
$conversation_id = base64_decode($_GET['c_id']);
$querynew = "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'";
$mysqli_q_new = mysqli_query($connection, $querynew);
confirmQuery($mysqli_q_new);
if (mysqli_num_rows($mysqli_q_new) > 0 ){
while($user_real_info = mysqli_fetch_assoc($mysqli_q_new)){
$trap_user_from = $user_real_info['user_from'];
$trap_user_to = $user_real_info['user_to'];
$trap_user_message = $user_real_info['message'];
$querynew2 = "SELECT profile_image,firstname FROM `users` WHERE id='$trap_user_from'";
$mysqli_q_new2 = mysqli_query($connection, $querynew2);
confirmQuery($mysqli_q_new2);
$user_fetch = mysqli_fetch_assoc($mysqli_q_new2);
$user_form_username = $user_fetch['firstname'];
$user_form_img = $user_fetch['profile_image'];
?>
<div class='conversation_history_inner clearfix'>
<span><?php echo $user_form_username; ?> </span>
<div class='converstion_history_image img-is-responsive pull-left'>
<?php echo getUserImage($user_form_img) ?>
</div>
<div class='converstion_history_chat'>
<p><?php echo $trap_user_message; ?></p>
</div>
</div>
<?php
}
}
} else {
echo 'nth found';
}
?>
答案 0 :(得分:1)
我假设您只想在收到第一条消息时向下滚动。如果是这样,我建议将stateChange
函数更改为:
var scrolled = false;
function stateChange() {
if(!scrolled){
$(".conversation_history.clearfix").animate({scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight}, 1000);
scrolled = true;
}
}
这样只会在第一次收到新邮件时向下滚动,而不是像目前那样每次都向下滚动。
答案 1 :(得分:0)
内容自动滚动到底部,因为您使用了setInterval
函数,该函数将以恒定的时间间隔触发。使用setTimeOut
代替它只会在指定时间后调用一次。查看here了解更多详情