Javascript自动滚动div

时间:2017-02-21 15:57:47

标签: javascript html

我想在div的末尾滚动,所以在我的情况下,我可以看到聊天的最后一条消息。 这就是我所拥有的,但它不起作用,滚动实际上位于div之上。

<script type="text/javascript">
var divChat = document.getElementById('chat');
divChat.scrollTop = divChat.scrollHeight;
</script>
<div id="chat" style="border-style:groove;overflow-y: auto; height:50%;">
<?php 
    $response = $bdd->query('SELECT * FROM minichat');
    while ($rsp = $response->fetch())
    {
        echo '['.$rsp['date_message'].']'." <strong>".htmlspecialchars($rsp['pseudo'])
        ."</strong>: ".htmlspecialchars($rsp['message'])."<br>";
    }
?>
</div>

感谢提前帮助,

1 个答案:

答案 0 :(得分:1)

这应该可以正常工作:

<div id="chat" style="border-style:groove;overflow-y: auto; height:50%;">
<?php 
    $response = $bdd->query('SELECT * FROM minichat');
    while ($rsp = $response->fetch())
    {
      echo '['.$rsp['date_message'].']'."         <strong>".htmlspecialchars($rsp['pseudo'])
    ."</strong>: ".htmlspecialchars($rsp['message'])."<br>";
    }
?>
</div>
...
<script type="text/javascript">
  var divChat = document.getElementById('chat');
  divChat.scrollTop = divChat.scrollHeight;
</script>
</body>