除非用户手动滚动,否则带滚动条的AJAX聊天窗口将保持在同一位置

时间:2018-02-28 17:14:43

标签: javascript php jquery ajax

这是我的JavaScript代码

var b = document.getElementById('chat');
b.scrollTop =b.scrollHeight;

但它不起作用。我使用AJAX更新了动态聊天div,但即使添加了新消息,滚动条也会保持在同一位置。

如何自动更新职位以显示最新消息?

我的AJAX代码是:

function  ajax(){
     var id=document.getElementById("chat");
     var req = new XMLHttpRequest();

     req.onreadystatechange =function(){
         if(req.readyState==4 && req.status==200)
         {
              var res = req.responseText;
             id.innerHTML=res;
         }                  
      }
     req.open('POST','msg.php',true);
     req.send();
 }
setInterval(function(){ajax()},4000);

可能是我的错误?

1 个答案:

答案 0 :(得分:0)

数据显示后你最好运行脚本。你试试这个代码

function  ajax(){
     var id=document.getElementById("chat");
     var req = new XMLHttpRequest();
      var oldscrollHeight = jQuery("#chat")[0].scrollHeight - 20;
     req.onreadystatechange =function(){
         if(req.readyState==4 && req.status==200)
         {
              var res = req.responseText;
             id.innerHTML=res;
             var newscrollHeight = jQuery("#chat")[0].scrollHeight - 20; //Scroll height after the request
                        if (newscrollHeight > oldscrollHeight) {
                            jQuery("#chat").animate({scrollTop: newscrollHeight}, '1000'); //Autoscroll to bottom of div
                        }

         }                  
      }
     req.open('POST','msg.php',true);
     req.send();
 }
setInterval(function(){ajax()},4000);