【问题标题】:automatically scroll chat height implementation still doesn't finish scrolling自动滚动聊天高度实现仍然没有完成滚动
【发布时间】:2021-11-01 12:19:33
【问题描述】:

链接这两个堆栈溢出帖子:

Chat box, auto scroll to bottom Automatically scroll down chat div

我已经尝试了两种解决方案:

const chatWindow = document.getElementById('chat-content');
chatWindow.scrollTop = chatWindow.scrollHeight;

const chatWindow = document.getElementById('chat-content');
const xH = chatWindow.scrollHeight;
chatWindow.scrollTo(0, xH);

现在是代码上下文中的代码:

this.twilioconversationservice.receiveworkingconversation()
      .subscribe(
        (req : any)=>{
          if(req != null){
            this.thisconversation = req;
            this.thisconversation.on('messageAdded', ()=>{
              this.thisconversation.getMessages().then((res: any)=>{
                this.messages = res.items;
                const chatWindow = document.getElementById('chat-content');
                chatWindow.scrollTop = chatWindow.scrollHeight;
              });
            });
          }
        });

但是从这篇文章中包含的图片可以看出,滚动条还没有完成滚动。到最后发送的消息不在视图中的位置。

这是代码问题吗?还是我在错误的时间滚动?

【问题讨论】:

  • 这不是一些时间错误的问题吗?我认为当您收到chatWindow.scrollHeight 时,新消息尚未完成呈现。
  • 但是我们将如何解决这个问题。设置的超时可能会说 400 毫秒或其他什么。但是当聊天真正进行并且我们收到大量消息时会发生什么?那不会引起冲突吗?

标签: javascript html css twilio chat


【解决方案1】:

所以至少我认为这有点像 hack,但不管怎样。我刚刚添加了一个 500 毫秒的 setTimeout

检查一下

this.twilioconversationservice.receiveworkingconversation()
      .subscribe(
        (req : any)=>{
          if(req != null){
            this.thisconversation = req;
            this.thisconversation.on('messageAdded', ()=>{
              this.thisconversation.getMessages().then((res: any)=>{
                this.messages = res.items;
                setTimeout(()=>{
                  const chatWindow = document.getElementById('chat-content');
                  chatWindow.scrollTop = chatWindow.scrollHeight;
                },500);

              });
            });
          }
        });

【讨论】:

  • 您如何呈现这些消息?您可能能够在渲染时触发滚动,而不是等待 setTimeout。此外,当您收到 messageAdded 事件时,消息的详细信息应该在事件对象中。因此,您应该能够将新消息附加到现有的消息列表中,而不是使用 getMessages 再次加载所有消息。
猜你喜欢
  • 1970-01-01
  • 2010-10-18
  • 2014-10-19
  • 2014-05-16
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
相关资源
最近更新 更多