简体   繁体   English

如何自动向下滚动聊天框 (div)?

[英]How do I scroll down a chatbox (div) automatically?

I've been working on a chat application and now I need to scroll automatically when a message appears.我一直在开发一个聊天应用程序,现在我需要在出现消息时自动滚动。 I've tried different things but they do not work unfortunately.我尝试了不同的东西,但不幸的是它们不起作用。 So this is my main.js code:所以这是我的 main.js 代码:

var lastTimeID = 0;

$(document).ready(function() {
  $('#btnSend').click( function() {

    sendChatText();
    $('#chatInput').val("");
  });
  startChat();
});

function startChat(){
  setInterval( function() { getChatText(); }, 2000);

}

function getChatText() {
  $.ajax({
    type: "GET",
    url: "/refresh.php?lastTimeID=" + lastTimeID
  }).done( function( data )
  {
    var jsonData = JSON.parse(data);
    var jsonLength = jsonData.results.length;
    var html = "";
    var message = $('#view_ajax');
    for (var i = 0; i < jsonLength; i++) {
      var result = jsonData.results[i];
      html += '<div>(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
      lastTimeID = result.id;

    }
    $('#view_ajax').append(html);
    message.html(data);
      message.scrollTop(message[0].scrollHeight);

  });
}

function sendChatText(){
  var chatInput = $('#chatInput').val();
  if(chatInput != ""){
    $.ajax({
      type: "GET",
      url: "/submit.php?chattext=" + encodeURIComponent( chatInput )
    });
  }
}

I've used我用过

var message = $('#view_ajax');
message.html(data);
message.scrollTop(message[0].scrollHeight);

I really have no clue how jQuery works.我真的不知道 jQuery 是如何工作的。 I've tried a couple of things before this but it didn't work also.在此之前我已经尝试了几件事,但它也不起作用。

Do you have any suggestion?你有什么建议吗? Any advice?有什么建议吗? Do you need any more information?你需要更多信息吗? Feel free to ask!随意问!

Give each message an ID, as follows:为每条消息指定一个 ID,如下所示:

<div id="msg-1234">

Then you can scroll to this element using this jQuery:然后你可以使用这个 jQuery 滚动到这个元素:

$('html, body').animate({ scrollTop: $('#msg-1234').offset().top }, 'slow');

Alternatively, put a div at the bottom of your chat:或者,在聊天底部放置一个 div:

<div id="chat-end"></div>

And scroll to this ID instead.并滚动到此 ID。

JSFiddle Demo JSFiddle 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM