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

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

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

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

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


当前回答

为什么不使用简单的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' });

如果这样做是为了滚动到聊天窗口的底部,请执行以下操作

在聊天中滚动到特定div的想法如下

1)每个聊天div由Person, time和message组成,在一个带有类chatContentbox的for循环中运行

2) querySelectorAll查找所有这样的数组。可以是400个节点(400个聊天)

3)最后一个

4) scrollIntoView ()

let lastChatBox = document.querySelectorAll('.chatContentBox'); 
lastChatBox = lastChatBox[lastChatBox.length-1]; 
lastChatBox.scrollIntoView(); 

试试下面的代码:

const scrollToBottom = (id) => {
    const element = document.getElementById(id);
    element.scrollTop = element.scrollHeight;
}

你也可以使用Jquery使滚动平滑:

const scrollSmoothlyToBottom = (id) => {
    const element = $(`#${id}`);
    element.animate({
        scrollTop: element.prop("scrollHeight")
    }, 500);
}

下面是演示

下面是它的工作原理:

参考:scrollTop, scrollHeight, clientHeight

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

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

将到可滚动元素顶部的距离设置为元素的总高度。

const element = this.shadowRoot.getElementById('my-scrollable-div')
element.scrollTop = element.scrollHeight