我正在處理類似於Facebook的消息框,該消息框在其中顯示消息。我得到它的工作,所以它刷新DIV每5秒內的消息,但是我試圖用設置滾動至底部:使用Javascript/Ajax存在問題
var div = document.getElementById('chat');
var y = (div.scrollHeight > div.offsetHeight) ? div.scrollHeight :div.offsetHeight;
div.scrollTop = y;
window.scrollTo(0, y);
這僅適用於我刷新DIV之前,任何人都可以向我解釋這個怎麼做?
此外,有沒有辦法通過發送請求到同一頁面來刷新div?
function ajax() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('messages').innerHTML = xmlhttp.responseText;
setTimeout(function() {
ajax();
}, 5000);
}
};
xmlhttp.open('GET', 'refresh.php', true);
xmlhttp.send(null);
}
}
setTimeout(function() {
ajax();
}, 5000);
<div id="messages">
<table id="chatbox">
<thead>Admin</thead>
<tfoot>
<td>
<textarea id="chattextbox" name="text"></textarea></td>
</tfoot>
<tbody>
<td>
<div id="chat">
<?php read_message($db); ?>
</div>
</td>
</tbody>
</table>
<style>
#chatbox {
overflow: scroll;
overflow-x: hidden;
word-wrap: !important;
height: 400px;
width: 300px;
padding: 0px;
border-right: solid 1px;
border-left: solid 1px;
border-top: solid 1px;
border-bottom: solid 1px;
resize: none;
max-width: 200px;
}
#chat {
overflow: scroll;
overflow-x: hidden;
word-wrap: break-word;
height: 400px;
width: 300px;
padding: 0px;
resize: none;
max-width: 300px;
}
#chattextbox {
width: 300px;
resize: none;
padding: 0px;
}
</style>
</div>
<script type="text/javascript">
var div = document.getElementById('chat');
var y = (div.scrollHeight > div.offsetHeight) ? div.scrollHeight : div.offsetHeight;
div.scrollTop = y;
window.scrollTo(0, y);
</script>
首先,「刷新div」的含義是什麼(標準網絡條款中沒有這種東西,因此您需要澄清)。其次,你會考慮使用一個DOM操作庫,比如JQuery嗎?他們通常會使解決這樣的問題變得更容易。 – machineghost
顯示你的ajax代碼,我敢肯定,你正在發出一個異步ajax請求,所以你的代碼allways工作之前刷新... – ocanal
這是我所有的我的ajax代碼和刷新div我的意思是我打電話我的PHP功能檢查消息,並用新的信息替換舊的div使用'innerHTML = x' – HurricaneChris