我正在设计一个基本的聊天网页,但是每当消息数量超过屏幕在不向下滚动的情况下可以显示的数量时,您就必须向下滚动才能看到更新的消息。有没有办法解决这个问题,以便在发送新消息时网页自动滚动(或类似的解决方案)? 任何帮助将不胜感激。 这是我的 HTML:
<!doctype html>
<html>
<head>
<title>QuickChat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; text-align: center; }
form { background: #666666; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 100; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: #FFCC00; border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
main {text-align: center; margin: 0; }
</style>
<form action="">
<input id="m" autocomplete="off" /><button>Send!</button>
</form>
<text>[SYSTEM]: Welcome to the chat! two things you should know: 1. There are no usernames.
I'm working on it, but for right now you can type your messages like [your name] [your message].
2. This chat is fairly secure, but PLEEEASE don't send any secret stuff accross it (like passwords) unless absolutely necessary.
Thanks for using my website! -C
</text>
</head>
<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(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text('[USER]: ' + msg));
});
});
</script>
<body>
<div id="main">
<ul id="messages"></ul>
</div>
</body>
</html>
最佳答案
您可以调用scrollIntoView()
关于<li>
,当您附加它时,例如:
$('<li>').text('[USER]: ' + msg).appendTo('#messages').get(0).scrollIntoView();
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
The
Element.scrollIntoView()
method scrolls the element on which it's called into the visible area of the browser window.
您还应该设置scroll-behavior
至smooth
在样式表中,阻止浏览器“跳转”到目标。
https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior
The
scroll-behavior
CSS property specifies the scrolling behavior for a scrolling box when scrolling is triggered by one of the navigation or CSSOM scrolling APIs.
关于javascript - 有没有办法使某些组件(即 <div>)在网页上自动滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51581260/