我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。

我将所有内容都包装在这个div中:

#scroll {
    height:400px;
    overflow:scroll;
}

是否有一种方法来保持它滚动到底部默认使用JS?

有办法保持它滚动到ajax请求后的底部吗?


当前回答

Javascript或jquery:

var scroll = document.getElementById('messages');
   scroll.scrollTop = scroll.scrollHeight;
   scroll.animate({scrollTop: scroll.scrollHeight});

Css:

 .messages
 {
      height: 100%;
      overflow: auto;
  }

其他回答

为什么不使用简单的CSS来做到这一点呢?

诀窍是使用display: flex;和弯曲方向:列反向;

Here is a working example. https://codepen.io/jimbol/pen/YVJzBg

像你一样,我正在构建一个聊天应用程序,并希望最近的消息滚动到视图中。这最终对我很有效:

//get the div that contains all the messages
let div = document.getElementById('message-container');

//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });

Javascript或jquery:

var scroll = document.getElementById('messages');
   scroll.scrollTop = scroll.scrollHeight;
   scroll.animate({scrollTop: scroll.scrollHeight});

Css:

 .messages
 {
      height: 100%;
      overflow: auto;
  }
var mydiv = $("#scroll");
mydiv.scrollTop(mydiv.prop("scrollHeight"));

来自jQuery 1.6的工作

https://api.jquery.com/scrollTop/

http://api.jquery.com/prop/

Java脚本:

getElementById(‘messages)文件。scrollIntoView(虚假);

滚动到当前内容的最后一行。