首页 > 解决方案 > 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!!

标签: javascripthtml

解决方案


您需要为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>


推荐阅读