javascript - 当用户与站点交互时禁用自动滚动 'scrollToBottom' 功能

标签 javascript html css node.js socket.io

当然,这个问题已经被以不同的方式提出和回答,但我是一个菜鸟,我迷路了。我正在关注 WebDevJourney 在 YouTube 上发布的关于 Node.js、Socket.io 和聊天应用程序的教程;他跳过了实现“当用户滚动旧消息并且另一个用户发布消息时禁用滚动到底部”的部分,因为通过快速 Google 搜索应该很容易解决这个问题。

我在 Chrome 中发布了一个自动点击功能来发布消息。然后在另一个窗口中,表现得像另一个用户。我希望能够滚动和阅读旧消息,而不是每次我的自动点击用户发布新消息时都看到底部。

这些可能让我最接近解决方案: Keep overflow div scrolled to bottom unless user scrolls up还有这个Keep the scroll at the bottom unless user changes the position of the scroll .

两天后,我在这里,成为我自己的坚持(或愚蠢)的牺牲品,我希望得到帮助。

这在前面提到的函数中:

function scrollToBottom () {
  let messages = document.querySelector('#messages').lastElementChild;
  messages.scrollIntoView();
}

在创建新消息的函数中调用该函数:

socket.on('newMessage', function (message) {
  const formattedTime = moment(message.createdAt).format('LTS');
  const template = document.querySelector('#message-template').innerHTML;
  const html = Mustache.render(template, {
    from: message.from,
    text: message.text,
    createdAt: formattedTime
  });

  const div = document.createElement('div');
  div.innerHTML = html;

  document.querySelector('#messages').appendChild(div);
  scrollToBottom();
});

我的 div 看起来像这样:

    <div class="chat__main" id="scrollsolve">
        <ol id="messages" class="chat__messages"></ol>

        <div class="chat__footer">
            <form id="message-form">
                <input name="message" type="text" placeholder="Message" autofocus autocomplete="off" />
                <button type="submit" id="submit-btn">Send</button>
            </form>
            <button type="button" id="send-location">Send Location</button>
        </div>
    </div>

我的 div 是用这样的 CSS 设计的:

.chat__main {
    display: flex;
    flex-direction: column;
    height: 100vh;
    width: 100%
}

.chat__messages {
    flex-grow: 1;
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
    padding: 10px
}

我尝试按照此处的指南进行操作,但我确定我错过了一些步骤!我希望代码量有助于澄清而不是混淆。如果不是,请写下可以进一步说明的内容。

最佳答案

这是我在聊天系统中用于自动滚动的代码。基本上它会检查滚动条是否在底部(或接近底部)并自动向下滚动。如果不是,那就不是。

只需将数字 450 更改为您认为合适的任何值即可。数字越小,阈值越小:

const elem = document.getElementById('messages');
const scrollDiff = (elem.scrollHeight - elem.scrollTop) - elem.clientHeight;

if(scrollDiff < 450){
    elem.scrollTop = elem.scrollHeight;
}

您应该能够将其放入您的 scrollToBottom () 函数中。

关于javascript - 当用户与站点交互时禁用自动滚动 'scrollToBottom' 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792967/

相关文章:

html - 内容后面的下拉菜单

javascript - 将 python 回调函数转换为 javascript

PHP mysql 而不是根据数据库键分配变量

html - 图像不适用于容器宽度的 50%

html - 如何找到类名和通用属性的 xpath?

html - Bootstrap 垂直对齐与列环绕和不同高度

javascript - 使用动画单击按钮时需要移动到顶部

javascript - Google map - 如何在标记数组中定位标记?

javascript - 使用 CSS 或 Javascript 复制/剪切时从文本中删除样式

javascript - 无法更改条件内的 var