javascript - HTML Javascript Automatic Window Scroll
问题描述
Thanks in advance for any time you (the reader) spends to help me out and to understand what I am doing wrong. I am new to JS and HTML, and am teaching myself through the internet, so take this with a grain of salt. I might just not know enough and the answer is obvious to someone with more knowledge than me. :)
I am trying to make a simple (for now) "Hacking simulator" game that is command line based, with a custom HTML command line. You can view my full code (less than 500 lines) on GitHub:
https://github.com/qcontom/Hacking-Protocol
However, I have run into a slight problem, and cannot seem to find an answer that relates to my project on the web. I want to have my "terminal" window automatically scroll as the user enters in commands. The closest thing that I can find online to do this is:
const console = document.getElementById('terminal');
function scrollToBottom() {
console.scrollTop = console.scrollHeight;
}
Where "terminal" is the HTML window that I want to automatically scroll.
What am I missing or doing incorrectly that causes the program to not scroll? Any help, or direction to a tutorial I might have missed, would be GREATLY appreciated!
Once again, thanks for your time!!
解决方案
您需要为max-height
您的终端元素定义 a ,否则它将不起作用。并平滑滚动添加scroll-behavior: smooth;
。
除非定义了 max-height 并定义了属性,否则 Elements 不会创建您自己的滚动条overflow: auto|scroll
。而且,如果您的内容溢出。
max-height
没有强制创建滚动的元素window
,因此您需要使用scrollTo
来自window
对象的方法。除非定义了 max-height 并定义了属性,否则 Elements 不会创建您自己的滚动条overflow: auto|scroll
。
另一种方法是滚动窗口,以防您的终端没有最大高度。为此用途:
window.scrollTo( {
top: 300000,
behavior: "smooth"
});`
function scrollToBottom() {
el = document.getElementById('console');
el.scrollTop = el.scrollHeight
setTimeout( function() {
window.scrollTo( {
top: 300000,
behavior: "smooth"
});
}, 1000 );
}
#console {
max-height: 200px;
margin: 20px;
overflow: auto;
border: 1px solid blue;
scroll-behavior: smooth;
}
p {
height: 500px;
}
#scroll {
min-height: 2000px;
}
<div id="console">
<button onclick="scrollToBottom()">Click Me</button>
<p></p> <!--only to force scroll -->
</div>
<div id="scroll"></div>
推荐阅读
- ios - 设置和删除 UIButton 文本标签
- javascript - 从 forEach 循环返回数组而不使用其他函数
- php - 如何在 Wordpress 摘录中的 Read More 链接之前向元素添加“...”?
- sql - 基于查询的 Postgres SQL 列别名
- android - Flutter dart:如何分隔Text和TextField之间的空间并同时汇集RadioListTile?
- php - 在 mlm 二进制计划中实施溢出系统,以在选定侧的最后一个可用子节点上加入用户
- python - 如何以表格形式显示 azure 资源 python SDK
- angular - 如何修复:ngRx 中的“TypeError:实体不可迭代”
- unit-testing - 如何最好地对使用 IServiceGateway 调用其他内部服务的 ServiceStack 服务进行单元测试
- shell - 如何在命令中使用空格来使用别名 cd 到目录及其子目录?