无法向上滚动div内容

我创建了一个简单的聊天应用程序。 我已经使用setTimeout每隔0.5毫秒刷新一次消息,并使用scrolltop将滚动条保持在底部。 但问题是无法向上滚动消息div。

   Live Table Data Edit      



You Are :


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 });

当我将setTimeout放在scrolltop下面时,返回false语句会停止执行,但之后我就可以向上滚动了。

每次有新消息时,你真的需要滚动到消息div的底部吗? 大多数消息应用程序都不这样做; 它们只在查看消息开始时滚动到底部,因为您想要查看最新的消息。

运行代码段。 请注意,自动滚动到底部只执行一次,如果有新消息,我的滚动位置保持不变(因为我还在阅读),但添加了新消息。

 $(document).ready(function(){ var i = 1; setInterval(fillUpChat,2000); var div_to_scroll = $("#messages-container")[0]; div_to_scroll.scrollTop = div_to_scroll.scrollHeight; function fillUpChat(){ $("#messages").append("
  • New Message "+i+"
  • "); i++; } });
     #messages-wrapper{ height:200px; border:1px solid black; padding:10px; } #messages-container{ height:100px; overflow-y:auto; border:1px solid black; } 
      
    • Old Message
    • Old Message
    • Old Message
    • Old Message
    • Old Message
    • Old Message
    • Old Message
    • Old Message
    • Old Message

    使用javascript的setInterval函数而不是递归调用函数;

     //call request Chat every 2 seconds var fetchChatRepeat = setInterval(fetchChat ,2000); function fetchChat() { $.ajax({ url: "fetch_chat.php", method: "POST", data: { id: currentID }, dataType: "text", success: function(data) { $("#messages").show(); $('#messages').html(data); $("div.area").show(); } }); }