问题描述
我正在解决奇怪的Chrome行为,当页面加载时,它会跳到页面底部,然后立即回到顶部。
可复制
- Chrome 84.0.4147.135(正式版本)
- 铬80.0.3987.162
条件
当两个条件都成立时,就会发生问题。页面跳到底部(有一个红色的div-闪烁红色),然后立即回到顶部(再次变成白色)。
当只有'#bottom'片段没有javascript或只有javascript没有'#bottom'片段时,所有片段都可以正常工作-当页面滚动到最底部时,页面为红色。仅当同时使用两种机制时,它才起作用。
预期行为
当前行为:
注意:Chrome似乎只是恢复了初始滚动位置。当您从底部开始并单击“ CTRL + R”时,它将停留在底部。当您从顶部开始并按CTRL + R时,它将停留在顶部,同时在页面的底部短暂跳转。
简化代码:
<!DOCTYPE html>
<html>
<body>
<!-- Just a button that makes sure there is '#bottom' fragment in URL,resets scrolling and reloads page -->
<a href="javascript:location='#bottom';document.documentElement.scrollTop=0;location.reload();" style="position: fixed;">
CLICK TO TEST
<div><small>Keep clicking and if you see RED BACKGROUND FLASH you can reproduce the problem.</small></div>
</a>
<!-- Two big divs with distinct colors so we can see color flash when it jumps -->
<div id="top" style="background: white; height: 10000px;"></div>
<div style="height: 500vh; background-color: red;"></div>
<!-- bottom target referenced by '#bottom' above -->
<div id="bottom">BottOM ANCHOR</div>
<script type="text/javascript">
document.documentElement.scrollTop = document.documentElement.scrollHeight;
</script>
</body>
</html>
我无法使用嵌入式预览,因为它需要带片段的URL。您可以在here上实时看到它。
编辑:观察-整个问题似乎是Chrome试图保留旧的scrollTop位置,尽管Javascript将其更改为新的位置。
解决方法
这不是错误。发生了什么事:
- 由于JS设置了URL的哈希值,因此页面向下滚动。
- 由于JS设置了
scrollTop
属性,因此页面被向上滚动。 - 页面重新加载(需要一些时间)。
- 由于哈希仍为
#bottom
,一旦浏览器找到ID为bottom
的元素,它就会滚动到它。
我不知道最好的解决方法是什么,但这似乎可行:
javascript:location.hash='#bottom';document.documentElement.scrollTop=0;undefined;