私は2人のユーザー間でチャットするためのスクリプトを作成しました。私はスクロールバーが(ほとんどのチャットアプリケーションで行われたように)下に行きたいと思って、ユーザーが新しいテキストを再び入力したときに、スクロールバーは一番下の位置にとどまります。また、チャットボックスを0.5msごとにリフレッシュして、両方のチャットユーザーのためにリアルタイムで行われるようにしたい。setTimeout関数を実行して同時に下にスクロールする方法
<script>
var currentID = null;
var chatTimer = null;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
//fetch_chat();
}
});
}
function fetchChat() { // 30% of chance of having new message
if (Math.random() <= 0.3) {
$("#messages").append("<div>" + "Random message " + Math.random() + "</div>");
// Scroll to bottom if you are at bottom, with tolerance of 50px
if ($(window).scrollTop() + $(window).height() > $(document).height() - 50) {
scrollToBottom();
}
}
}
function sendMessage(txt) {
$("#messages").append("<div>" + txt + "</div>");
$.post('insert_chat.php', {
id: currentID,
msg: txt
}, function(data) {
});
scrollToBottom();
}
function scrollToBottom() {
$(window).scrollTop(1e10); // Lazy hack
}
setInterval(function() {
fetchChat();
}, 500);
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#messages").show();
$('#messages').html(data);
$("div.area").show();
//chatTimer = setTimeout(fetch_chat, 500); //request the chat again in 2 seconds time
// $("#messages").animate({ scrollTop: $(document).height() }, "fast");
// return false;
if ($(window).scrollTop() + $(window).height() > $(document).height() - 50) {
scrollToBottom();
}
}
});
}
$(document).ready(function() {
fetch_data();
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
//immediately fetch chat for the new ID, and clear any waiting fetch timer that might be pending
// clearTimeout(chatTimer);
fetch_chat();
});
$("#text").keydown(function(e) {
if (e.keyCode == 13) {
sendMessage($("#text").val());
$("#text").val("");
}
})
//this will also trigger the first fetch_chat once it completes
});
</script>
ここにスクリプトがあります。私は、スクロールバーを下にしたいが、ユーザーが前のメッセージをスクロールアップするときにもうまくいくはずです。私のdoesntのcozではfetch_chat()に入れました。 Plz私は私に希望の出力を得るために助けてください。
しかし、また、わずか5分、私はOPはミリ秒を意味推測 –
理由.....それはリアルタイムで行われるようにチャットボックスごとに0.5ミリ秒をリフレッシュしたいです。しかし、コードでは500ミリ秒なので、0.5秒です。 – Connum
@connumはいu r右。 –