首页 > 解决方案 > 单击锚点后如何刷新页面并加载到顶部,忽略锚点并重置回顶部?

问题描述

我有一个带有几个锚点的页面。当用户单击锚点时,锚点起作用,用户被带到正确的位置。

如果用户尝试刷新页面,它会在 URL 窗口中保留锚点 ID,因此在刷新时,它自然不会回到页面顶部。

我认为在刷新时返回页面顶部会更加用户友好。

我将如何实现这一目标?

我的页面目前主要使用 bootstrap、css、jquery、javascript 和 php。

我想我需要设置一些代码,以便在单击锚点后,它会从 url 窗口中删除锚点,这样如果有人刷新,他们只会刷新没有锚点的初始页面状态,但我没有知道如何开始。或者也许我想太多了,有一些方法可以在刷新时始终转到页面顶部,而不管锚点与否。我不太精通代码。

现在我的代码是这样的......

我的一个锚的例子:


<a class="hoverlink" href="#firefighter"><li style="float:left; margin-right:1em; color:white; background-color:red" class="appao-btn nav-btn">Fire Fighter</li></a>

例如,锚点将跳转到的元素之一:


<div style="min-height:10px;" name="firefighter" id="firefighter" class="anchor"><p style="min-height: 10px;">&nbsp;</p></div>

我的锚点上的 CSS 样式:

.anchor:target { height:200px; display: block; margin-top:-2em; visibility: hidden;}

我的代码的实际结果:页面刷新停留在锚点位置

期望的结果:页面刷新到页面顶部


经过一番搜索,我找到了一个几乎对我有用的解决方案:

<script>
window.onbeforeunload = function () {
  window.scrollTo(0, 0);
}
</script>

但它会产生一种看起来不是最好的闪烁效果,例如我的示例网站

https://graceindustries.com/gracetest/Grace%20Industries%20Website%20Design%202019%20Alternate%20Version/documentation.html

有人知道如何消除“闪烁”吗?

标签: htmlscrollrefreshanchor

解决方案


您可以在用户单击锚标记后立即从 url 中删除 id

history.scrollRestoration = "manual"将在刷新时将滚动设置到页面顶部

<a onclick="removeAnchorFormURL()" href="#sec-2">here</a>

<script>
  history.scrollRestoration = "manual";

  const removeAnchorFormURL = () => {
    setTimeout(() => {
      window.history.replaceState({}, "", window.location.href.split("#")[0]);
    }, 100);
  };
</script>

window.location 文档

location.href 文档

location.replace 文档

scrollRestoration 文档(检查它以获取有关 scrollRestoration 兼容性的信息)


推荐阅读