setTimeout()函数停止滚动

时间:2017-11-04 18:19:07

标签: jquery ajax

我创建了一个简单的聊天应用。我使用setTimeout每隔0.5毫秒刷新一次消息,scrolltop将滚动条保持在底部。

    <?php
    session_start();
    ?>
       <html>  
       <head>  
       <title>Live Table Data Edit</title>  
       <link rel="stylesheet" 
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" 
    />  
        <script 
    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <body>  
           <div class="container">  
                <br />  
                <br />  
                <br />  
                <div class="table-responsive">  
                     <h3 align="center">You Are : <?php echo $_SESSION['name']; ?></h3><br />  
                     <div id="live_data"></div>                 
                </div>  
            <div id="messages" style="    border: 1px solid #ccc;
         width: 350px;
height: 210px;
padding: 10px;
overflow-y:scroll;
display:none;"></div> 
            <div class="area" style="display:none">
            <textarea id="text" name="text"style="    border: 1px solid #ccc;
width: 350px;
height: 50px;
padding: 10px;" ></textarea>
            <input type="submit" id="sub" name="sub" value="Send" />
                </div>
           </div>  


<script>
var currentID = null;
var chatTimer = null;

function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
  $('#live_data').html(data);
  //fetch_chat();
    }
  });
}

function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
  id: currentID
},
dataType: "text",
success: function(data) {
  $("#messages").show();
  $('#messages').html(data);
  $("div.area").show();

  $("#messages").animate({ scrollTop: $(document).height() }, "fast");
  return false;
   chatTimer = setTimeout(fetch_chat, 500); //request the chat again in 2 seconds time     
    }

  });
}

$(document).ready(function() {

  $(document).on('click', '.first_name', function() {
   currentID = $(this).data("id1");
   //immediately fetch chat for the new ID, and clear any waiting fetch 
     timer that might be pending
   clearTimeout(chatTimer);
   fetch_chat(); 
 });

$("#sub").click(function() {
var text = $("#text").val();

$.post('insert_chat.php', {
  id: currentID,
  msg: text
 }, function(data) {
  $("#messages").append(data);
  $("#text").val('');
  });
});

fetch_data();//this will also trigger the first fetch_chat once it completes
   });
   </script>
  </body>  
  </html>

根据我的需要,一切正常,但是当我使用setTimeout() {因为我现在正在使用}时,滚动卡住了,当我删除setTimeout滚动部分工作正常但其他用户无法实时查看新消息,因为它们并不令人耳目一新。

1 个答案:

答案 0 :(得分:0)

您的代码按预期运行。每隔5ms将滚动设置到顶部。这实际上抵消了用户滚动的任何尝试,因为滚动每5ms重置一次。

一些选择:

使用固定大小的div来保存聊天,然后相应地管理内容。

使其成为只有在有新消息时才更新滚动条。您可以通过etags或缓存最后一条消息并验证下一个请求是否具有相同的最后一条消息来完成此操作。

相关问题