什么会导致滚动到顶部?

时间:2021-04-16 08:28:06

标签: javascript reactjs scroll

React 中的页面总是在 history 导航中滚动到顶部。我无法弄清楚导致滚动到顶部的原因。

  • 没有window.scrollTo()可以做到这一点
  • 没有 .focus() 事件专注于更高的元素并移动滚动位置
  • 大的 React 组件不会卸载,这会导致页面变短,从而移动滚动位置

那么还有什么可以导致 document.documentElement.scrollTop 被设置为 0

1 个答案:

答案 0 :(得分:1)

过渡中是否有任何后备屏幕,可能是具有最小高度的加载/中间框架。您可以处理类似提到的React Router v4 - Keep scrolling position when switching components

function buttonClick() {
    document.getElementById("myDiv").classList.add("reduceHeight");
    setTimeout(()=>document.getElementById("myDiv").classList.remove("reduceHeight"),2000);
  }
#myDiv {
  border: 1px solid black;
  width: 100vw;
  height: 200vh;
  overflow: scroll;
}
#myDiv.reduceHeight {
  width: 80vw;
  height: 90vh;
}
button {
  position: fixed;
  top:100px;
  right:100px;
  z-index:100;
  width:200px;
}
<!DOCTYPE html>
<html>
<body >
<div id="myDiv">
  Scroll and Click the Simulate Button
  
</div>

<button onClick="buttonClick()">Simulate intermediate!</button>
</body>
</html>