我如何重新加载页面并跳转到锚点?

问题描述 投票:1回答:2

我正在尝试从服务工作者那里收到消息时刷新页面,这种情况发生在有新内容要显示时(这是刷新页面时锚点应该跳转到的内容。

所以想象我有这些:

var url = 'http://example.com/home.htm';
var anchor = '#comment-45';

并且具有该URL的页面已经加载。我想重新加载页面,然后跳转到#comment-45。

所有这些都不起作用:

这不会重新加载页面,只是尝试跳转到不存在的锚点:

 window.location = url+anchor;

更改为正确的URL并重新加载,但不会跳转到新的锚点:

    window.location.hash = anchor;
    window.location.reload(true);

OR

    window.location.href = url+anchor;
    window.location.reload(true);

将页面重新加载到基本URL,但不更改锚点:

    window.location = url;
    window.location.hash = anchor;
javascript
2个回答
1
投票

假设您添加

<a id="comment-45">Comment 45</a>

您可以在</body>之前的页面底部找到它>

<script>
const links = document.querySelectorAll("a[id]");
const lastLink = links[links.length-1];
if (lastLink) {
  window.location.hash = lastLink.id; // for bookmarking
  lastLink.scrollIntoView(); 
}
</script>

然后是

window.location.reload(1); 

将滚动到重新加载时的最后一个锚点


1
投票

根据我的经验,在许多情况下不会触发浏览器滚动到锚点。我发现了一个后备程序,该后备程序在URL中查找哈希/片段,并在加载时使用JS滚动到它,以使其更加可靠。如果可以添加锚点并使用概述的方法之一重新加载,则应该可以使用它来处理滚动:

© www.soinside.com 2019 - 2024. All rights reserved.