[英]Scroll to bottom of item on Ajax load
我正在用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;
}
}
這將使其僅在第一次收到新消息時向下滾動,而不是像當前那樣每次滾動。
內容自動滾動到底部,因為您使用了setInterval
函數,該函數將在固定的時間間隔觸發。 使用setTimeOut
代替,它將在指定時間后僅調用一次。 在這里查看更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.