Javascript scrollIntoView 仅在直接父级中

iAd*_*nct 5 html javascript

如何scrollIntoView仅滚动直接父级(例如div使用overflow-y: scroll;)而不滚动整个页面?

我有一个网络界面,我正在为一个内部的、非常具体的目的而制作。在我的页面上的其他元素是div具有指定高度,overflow-yscroll

我有数据会定期出现在这个区域,我希望它总是滚动到底部(例如某个远程服务器上子进程的控制台输出)。

如果我使用scrollIntoView,它会滚动overflow-y div..... 但也会滚动整个页面。

在带有大显示器的计算机上,这不是问题,但在我的屏幕较小的笔记本电脑上,它还会滚动整个窗口,这绝对不是预期/期望的行为。

Iai*_*ard 55

我想你可能正在寻找的是

.scrollIntoView({block: "nearest", inline: "nearest"});
Run Code Online (Sandbox Code Playgroud)

在支持的情况下(基本上除了 IE 和 SafarIE 之外的任何地方),这将执行“最少”的移动来显示元素;因此,如果外部容器可见,但目标元素隐藏在该容器内 - 那么它应该滚动内部容器而不是页面。

  • 这应该是公认的答案 (4认同)

dbr*_*ell 5

I think you're looking for a combination of scrollTop and scrollHeight. You can use the first to set where you want the div to scroll to, and the second to get the height of all the info in the div:

var scrollyDiv = document.getElementById("container");
scrollyDiv.scrollTop = scrollyDiv.scrollHeight

setInterval(() => {
  var textnode = document.createElement("P");
  textnode.innerHTML = "Whatever"
  scrollyDiv.appendChild(textnode);  
  scrollyDiv.scrollTop = scrollyDiv.scrollHeight
}, 1000)
Run Code Online (Sandbox Code Playgroud)
#container {
  height: 200px;
  overflow-y: scroll;
}

#big-content {
  height: 400px;
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
  <div id="big-content"></div>
  <p>The bottom</p>
</div>
Run Code Online (Sandbox Code Playgroud)