我正在使用 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';
}
?>
最佳答案
我假设您只想在收到第一条消息时向下滚动。如果是这样,我建议将 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;
}
}
这将使其仅在第一次收到新消息时向下滚动,而不是像当前那样每次都向下滚动。
关于javascript - 在 Ajax 加载时滚动到项目底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49612960/