【发布时间】:2019-08-17 09:01:04
【问题描述】:
我正在尝试在网页上创建一个聊天应用程序。我有一个正在发送的消息列表。问题是,最新消息不会使页面自动滚动到该消息。
我试过了:
socket.on('chat message', function (msg) {
$('#messages').append($('<li>').text(msg));
// then you can scroll down once to show the new messages
var elem = document.getElementsByName('#messages');
elem.scrollTop = elem.scrollHeight;
});
我也尝试过使用溢出:滚动选项 没有运气。以及位置:css 形式中的相对选项(这有点工作,但不幸的是,文本框在开始时位于网页的顶部,跟随消息向下 - 看起来像这样:)
我面临的问题似乎很像这个堆栈溢出页面
Scroll HTML page before it 'reaches' the bottom
但我没看懂标记为已解决的答案
这是我目前在我的 html 文档中的代码:
<!doctype html>
<html>
<head>
<title>HF-Chat</title>
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<style>
/* width */
::-webkit-scrollbar {
width: 6px;
}
/* Track */
::-webkit-scrollbar-track {
background: #2F3136;
border-radius: 5px;
}
/* Handle */
::-webkit-scrollbar-thumb {
background: #202225;
border-radius: 5px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font: 13px Roboto;
color:#DCDDDE;
background-color: #36393F;
}
form {
background: #36393F;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}
form input {
background: #484C52;
color:#DCDDDE;
border: 0;
padding: 10px;
width: 90%;
margin-right: .5%;
margin-left: .2%;
margin-bottom: .2%;
border-radius: 5px;
outline-color: transparent;
}
form button {
width: 9%;
background: #7289DA;
border: none;
padding: 10px;
margin-bottom: .2%;
border-radius: 5px;
}
#messages {
list-style-type: none;
margin: 0;
padding: 5px;
padding-bottom: 50px; /*Sets the distance between the textbox and bottom message once enough messages has been sent for the scrollbar to appear */
}
#messages li {
padding: 5px 10px;
background: #36393F;
border-bottom: 1px solid #484C52;
}
#messages li:nth-child(odd) {
background: #36393F;
}
</style>
</head>
<body>
<div>
<ul id="messages"></ul>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function (e) {
e.preventDefault(); // prevents page reloading
if ($('#m').val().startsWith("/")) {
socket.emit('user command', $('#m').val());
}
else{
socket.emit('chat message', $('#m').val());
}
$('#m').val('');
return false;
});
socket.on('chat message', function (msg) {
$('#messages').append($('<li>').text(msg));
// then you can scroll down once to show the new messages
var elem = document.getElementsByName('#messages');
elem.scrollTop = elem.scrollHeight;
});
});
</script>
</div>
<form action="">
<input id="m" autocomplete="off" /><button><font color="#DCDDDE">Send</font></button>
</form>
</body>
</html>
【问题讨论】:
标签: javascript html css node.js socket.io