像facebook聊天系统一样向上滚动加载数据

我正在开发一个聊天系统,我需要在Facebook聊天系统等滚动function上显示聊天记录。

有谁能够帮我?

它会像这样……

HTML

JQUERY

 $(document).ready(function(){ $("#chatBox").scrollTop($("#chatBox")[0].scrollHeight); $('#chatBox').scroll(function(){ if ($('#chatBox').scrollTop() == 0){ // Do Ajax call to get more messages and prepend them // To the inner div // How you paginate them will be the tricky part though // You'll likely have to send the ID of the last message, to retrieve 5-10 'before' that $.ajax({ url:'getmessages.php', data: {idoflastmessage:id}, // This line shows sending the data. How you get it is up to you dataType:'html', success:function(data){ $('.inner').prepend(data); $('#chatBox').scrollTop(30); // Scroll alittle way down, to allow user to scroll more }; }); } }); }); 

这里的例子

 // GENERATE FIRST BATCH OF MESSAGES //This will be where you do your SQL and PHP first for(var i=0;i<20;i++){ $('.inner').prepend('
First Batch messages
'+Date()+'
');} $("#chatBox").scrollTop($("#chatBox")[0].scrollHeight); // Assign scroll function to chatBox DIV $('#chatBox').scroll(function(){ if ($('#chatBox').scrollTop() == 0){ // Display AJAX loader animation $('#loader').show(); // Youd do Something like this here // Query the server and paginate results // Then prepend /* $.ajax({ url:'getmessages.php', dataType:'html', success:function(data){ $('.inner').prepend(data); }; });*/ //BUT FOR EXAMPLE PURPOSES...... // We'll just simulate generation on server //Simulate server delay; setTimeout(function(){ // Simulate retrieving 4 messages for(var i=0;i<4;i++){ $('.inner').prepend('
Newly Loaded messages
'+Date()+'
'); } // Hide loader on success $('#loader').hide(); // Reset scroll $('#chatBox').scrollTop(30); },780); } });
 body {font-family:Arial;} #chatBox {width:300px;height:400px;border: 1px solid;overflow:scroll} #loader {display:none;} .messages {min-height:40px;border-bottom:1px solid #1f1f1f;} .date {font-size:9px;color:#1f1f1f;}