简体   繁体   English

如何滚动到 div 底部(聊天) - 同步

[英]How to Scroll to bottom of div (chat) - synchronously

I'm trying to create a chat application.我正在尝试创建一个聊天应用程序。 Every time the user sends a new message, the new message gets appended to a ul list of messages.每次用户发送新消息时,新消息都会附加到 ul 消息列表中。 I have made the UL list scrollable and it is scrolling overtime I send a message;我已使 UL 列表可滚动,它正在滚动超时我发送一条消息; however it is not scrolling all the way to the bottom.但是它并没有一直滚动到底部。 FYI: I'm using Vue.js仅供参考:我正在使用 Vue.js

This is current code:这是当前代码:

this.messages.push(this.currentMessage) //adding new message to the list
var div = document.getElementById('chat-list-ul');
div.scrollTop = div.scrollHeight;

It somehow just scrolls to one line before the bottom.它以某种方式只是滚动到底部之前的一行。 Doing some testing I discovered that it maybe caused by the scroll function being called too fast, because if I insert a timeout of 1s, it will scroll correctly.做了一些测试,我发现它可能是由于滚动函数调用太快引起的,因为如果我插入 1s 的超时,它将正确滚动。

My question is: is there a way to create a promise for the array.push() function that will allow me to call the scroll method only after the array has gotten update with the new value?我的问题是:有没有办法为 array.push() 函数创建一个承诺,它允许我仅在数组使用新值更新后才调用滚动方法?

Thank you,谢谢,

You can use Vue.nextTick(callback) to wait for the DOM to be updated after pushing the new message before you trigger the scroll.您可以使用Vue.nextTick(callback)在推送新消息后等待 DOM 更新,然后再触发滚动。 Something like this ..像这样的东西..

this.messages.push(this.currentMessage) //adding new message to the list
Vue.nextTick(function () {
    var div = document.getElementById('chat-list-ul');
    div.scrollTop = div.scrollHeight;
})

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

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