当用户与网站交互时,禁用自动滚动“ scrollToBottom”功能

时间:2019-11-10 21:10:34

标签: 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
}

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

1 个答案:

答案 0 :(得分:0)

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

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

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

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

您应该可以将其放在scrollToBottom ()函数中。