我正在使用 react 创建一个需要在页面加载时滚动到底部的组件。首先我使用了 scrollTop
element.scrollTop = element.scrollHeight
但没有发生滚动。但是以下工作有效
element.scrollIntoView(false)
现在从 MDN ,我知道设置较高的 scrollTop
值应该告诉浏览器滚动到底部,并且它应该适用于所有最新版本的浏览器。难道是我的理解有误?
最佳答案
scrollTop
不用于移动元素或滚动位置。它的作用是:
Get the number of pixels the content of a
<div>
element is scrolled vertically
因此,要在页面中滚动,您需要使用 scrollIntoView
,这会将页面的当前 View 移动到您当前选择的元素中。如果您想移动到该元素的顶部或执行其他一些行为,您可以检查 the documentation关于这个方法。
The scrollIntoView() method scrolls the specified element into the visible area of the browser window.
关于javascript - 滚动顶部与 ScrollView : why scrollTop didn't work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56780773/