[英]JavaScript/PHP text appearing from bottom of div to top
我有一个聊天程序,该程序使用ajax运行php脚本来查询MYSQL DB,提取聊天详细信息并将其提供给javascript,然后将其推送到div。
目前,数据显示在div的顶部,并且一直向下移动,目标是使最新的注释从底部一直显示到屏幕上方。
当前代码段:
AJAX:
function displayChat() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("chat").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","displayChat.php?",true);
xmlhttp.send();
}
HTML聊天DIV
<div id="chat"></div>
PHP代码
$displayChat =mysql_query(
"select c.userID, u.userName, c.comments, c.datetime, c.tag
from chat c
inner join userAccounts u
on u.userID=c.userID
order by c.datetime ASC",
$connection);
while ($row = mysql_fetch_assoc($displayChat )) {
echo "(".$row['datetime'].")"." <b>".$row['userName']."</b>: ".$row['comments']."<br>";
}
CSS
#chat {
height: 90%;
overflow-y: scroll;
background-color: white;
text-align: left;
padding-left: 25px;
bottom: 0;
}
我该如何实现?
var current = document.getElementById("chat").innerHTML;
current.innerHTML = current.innerHTML + this.responseText;
如何将其添加到onreadystatechange AJAX函数中?
我认为这是您要搜索的内容:
// html
<div id="chat-wrapper">
<div id="chat-content">
text1<br>
text2<br>
</div>
</div>
// CSS
#chat-wrapper {
border: 1px #ededed solid;
height: 200px;
overflow-y: scroll;
background-color: white;
text-align: left;
position: relative;
}
#chat-content {
position: absolute;
bottom: 0;
left: 0;
padding-left: 25px;
}
那你当然需要改变这个
document.getElementById("chat").innerHTML = this.responseText;
至
document.getElementById("chat-content").innerHTML = this.responseText;
最好只将新添加的消息从服务器发送到客户端,否则可能会产生大量消息。 但这需要更多的工作。 (将最新传输的味精保存在客户端上,将该时间戳添加到请求中,...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.