我正在使用vanilla Javascript和AJAX构建一个AJAX聊天系统(所以没有jQuery)。消息通过AJAX加载并放入使用overflow-y: scroll;
的div中,以便您可以滚动浏览所有消息。
因为最新消息显示在底部,所以我有一个scrollDown()函数滚动到div的末尾:
function scrollDown()
{
var objDiv = document.getElementById("chatbox");
}
问题是这个功能不起作用。如果我window.onload = function() { scrollDown(); };
我也尝试了window.onload = scrollDown
,但这也无效。
我确信问题不在scrollDown()函数中,因为我还使用该函数在出现新消息时自动向下滚动,然后它运行良好。
这是我的完整源代码:
getBerichten();
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function doWork(id, user_id) {
nieuwbericht = getHTTPObject();
if (nieuwbericht != null) {
if( document.getElementById('bericht').value != "")
{
nieuwbericht.open("GET", "ajaxberichten.php?id=" + id + "&user_id=" + user_id + "&bericht="
+ document.getElementById('bericht').value, true);
nieuwbericht.send(null);
document.getElementById("bericht").value = "";
}
}
}
function setOutput()
{
if(httpObject.readyState == 4)
{
document.getElementById('berichten').innerHTML = httpObject.responseText;
//scrollDown();
setInterval(getBerichten(),1000);
}
}
function getBerichten()
{
httpObject = getHTTPObject();
if (httpObject != null)
{
httpObject.open("GET", "ajaxgetberichten.php?id=<?php echo $_GET['id'] ?>", true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
function scrollDown()
{
var objDiv = document.getElementById("chatbox");
objDiv.scrollTop = objDiv.scrollHeight;
}
window.onload = function() { scrollDown(); };
我的html页面:
<div class="postbox">
<div class="post">
<div class="chatbox" id="chatbox">
<div id="berichten"></div>
</div>
<form method="post" action="">
<textarea name="bericht" id="bericht"rows="20" cols="85"> </textarea>
<input name="verstuur" type="button" onclick="doWork(<?php echo $_GET["id"] ?>, <?php echo $user_id ?>);" value="Verstuur"/>
</form>
</div>
</div>
答案 0 :(得分:0)
尝试使用document.ready()而不是window.onload(),因为DOM在窗口事件上没有准备就绪