简体   繁体   English

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

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

I have a bunch of div elements that contain text and inputs.我有一堆包含文本和输入的div元素。 The first div is always visible.第一个div总是可见的。 Whenever a div 's input changes, next div becomes visible.每当div的输入发生变化时,下一个div就会变得可见。 I want to automatically scroll down the window as these new divs become visible, preferably having the last visible div in the vertical-center of the screen.当这些新的 div 变得可见时,我想自动向下滚动 window,最好让最后一个可见的div位于屏幕的垂直中心。

element.scrollIntoView({block: 'center'}) generally works, but it makes the top of the last visible div at the bottom of the window, so the user is forced to scroll further to see the inputs inside the div . element.scrollIntoView({block: 'center'})通常有效,但它使最后一个可见div的顶部位于 window 的底部,因此用户被迫进一步滚动以查看div内的输入。 I want the last div 's top to be in the center of the window and have empty space underneath the div until the next div is revealed.我希望最后一个div的顶部位于 window 的中心,并且在 div 下方有空白空间,直到显示下一个 div。 Is there a way to do this?有没有办法做到这一点?

You can use the Window.scrollTo() method to place the top of a div in the center of the viewport.您可以使用Window.scrollTo()方法将div的顶部放置在视口的中心。

This example will scroll to the fourth 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