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

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

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

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

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


当前回答

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

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

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

其他回答

滚动到div内的最后一个元素:

myDiv.scrollTop = myDiv.lastChild.offsetTop

这将允许您根据文档高度向下滚动

$('html, body').animate({scrollTop:$(document).height()}, 1000);

Javascript或jquery:

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

Css:

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

使用jQuery, scrollTop用于为任何给定元素设置scollbar的垂直位置。还有一个漂亮的jquery scrollTo插件,用于滚动动画和不同的选项(演示)

var myDiv = $("#div_id").get(0);
myDiv.scrollTop = myDiv.scrollHeight;

如果你想使用jQuery的animate方法在向下滚动时添加动画,请检查下面的代码片段:

var myDiv = $("#div_id").get(0);
myDiv.animate({
    scrollTop: myDiv.scrollHeight
  }, 500);

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

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