【发布时间】: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