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

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

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

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

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


当前回答

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

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

其他回答

以下是我在我的网站上使用的:

var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;

我使用了第一个项目div的Y坐标和所选项目div的Y坐标之间的差异。下面是JavaScript/JQuery代码和html:

function scrollTo(event){ // In my proof of concept, I had a few <button>s with value // attributes containing strings with id selector expressions // like "#item1". let selectItem = $($(event.target).attr('value')); let selectedDivTop = selectItem.offset().top; let scrollingDiv = selectItem.parent(); let firstItem = scrollingDiv.children('div').first(); let firstItemTop = firstItem.offset().top; let newScrollValue = selectedDivTop - firstItemTop; scrollingDiv.scrollTop(newScrollValue); } <div id="scrolling" style="height: 2rem; overflow-y: scroll"> <div id="item1">One</div> <div id="item2">Two</div> <div id="item3">Three</div> <div id="item4">Four</div> <div id="item5">Five</div> </div>

使用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);

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

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

我发现这真的很有用,谢谢。

对于Angular 1。在座的X位朋友:

angular.module('myApp').controller('myController', ['$scope', '$document',
  function($scope, $document) {

    var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
    overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;

  }
]);

只是因为在jQuery元素和HTML DOM元素中包装有点让人困惑。

同样对于聊天应用程序,我发现在你的聊天加载后进行分配是有用的,你也可能需要在短的超时。