繁体   English   中英

当元素是页面上的“最后一个元素”时,如何将元素滚动到 window 的中心

[英]How to scroll an element into center of window when it's the "last element" on the page

我有一堆包含文本和输入的div元素。 第一个div总是可见的。 每当div的输入发生变化时,下一个div就会变得可见。 当这些新的 div 变得可见时,我想自动向下滚动 window,最好让最后一个可见的div位于屏幕的垂直中心。

element.scrollIntoView({block: 'center'})通常有效,但它使最后一个可见div的顶部位于 window 的底部,因此用户被迫进一步滚动以查看div内的输入。 我希望最后一个div的顶部位于 window 的中心,并且在 div 下方有空白空间,直到显示下一个 div。 有没有办法做到这一点?

您可以使用Window.scrollTo()方法将div的顶部放置在视口的中心。

此示例将滚动到第四个 div:

 // scroll to the fourth div when button is clicked const divFour = document.getElementById('fourth'); const btn = document.querySelector('button'); btn.onclick = function() { // get height of the window const viewportHeight = window.innerHeight; // get position in the document of the div's top const elTop = divFour.offsetTop; // scroll window to locate top of div at middle of window window.scrollTo(0, elTop - (viewportHeight / 2)); }
 div { height: 250px; width: 80%; margin: 1rem; padding: 1rem; background-color: #e0e0e0; } #fourth { background-color: #a0a0a0; color: white; } button { position: fixed; top: 6px; right: 60px; z-index: 1024; font-size: 100%; }
 <body> <button>Scroll to fourth div</button> <div>first div</div> <div>second div</div> <div>third div</div> <div id="fourth">fourth div</div> <div>fifth div</div> <div>sixth div</div> </body>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM