【问题标题】:Disable auto scrolling 'scrollToBottom' function when user is interacting with the site当用户与网站交互时禁用自动滚动“scrollToBottom”功能
【发布时间】:2019-11-11 05:53:20
【问题描述】:

当然,这个问题已经被以不同的方式提出和回答,但我是一个菜鸟,我迷路了。我正在关注 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
}

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

【问题讨论】:

    标签: javascript html css node.js socket.io


    【解决方案1】:

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

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

    const elem = document.getElementById('messages');
    const scrollDiff = (elem.scrollHeight - elem.scrollTop) - elem.clientHeight;
    
    if(scrollDiff < 450){
        elem.scrollTop = elem.scrollHeight;
    }
    

    你应该可以把它放在你的 scrollToBottom () 函数中。

    【讨论】:

    • 非常感谢!这就是我的函数的结束方式,cmets 是旧函数: function scrollToBottom () { const elem = document.getElementById('messages'); const scrollDiff = (elem.scrollHeight - elem.scrollTop) - elem.clientHeight; if (scrollDiff
    • @PastOfTear 对我来说似乎很好。很高兴我能帮上忙:)
    猜你喜欢
    • 2011-11-28
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多