【问题标题】:What can cause scroll to top?什么会导致滚动到顶部?
【发布时间】:2021-07-11 06:31:28
【问题描述】:
React 中的页面总是滚动到history 导航的顶部。我无法弄清楚导致滚动到顶部的原因。
- 没有
window.scrollTo() 这样做
- 没有
.focus() 事件关注更高的元素并移动滚动位置
- 大型 React 组件不会卸载,这会导致页面变短,从而移动滚动位置
那么还有什么可以导致document.documentElement.scrollTop 被设置为0?
【问题讨论】:
标签:
javascript
reactjs
scroll
【解决方案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>