html - 单击锚点后如何刷新页面并加载到顶部,忽略锚点并重置回顶部?
问题描述
我有一个带有几个锚点的页面。当用户单击锚点时,锚点起作用,用户被带到正确的位置。
如果用户尝试刷新页面,它会在 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;"> </p></div>
我的锚点上的 CSS 样式:
.anchor:target { height:200px; display: block; margin-top:-2em; visibility: hidden;}
我的代码的实际结果:页面刷新停留在锚点位置
期望的结果:页面刷新到页面顶部
经过一番搜索,我找到了一个几乎对我有用的解决方案:
<script>
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
</script>
但它会产生一种看起来不是最好的闪烁效果,例如我的示例网站
有人知道如何消除“闪烁”吗?
解决方案
您可以在用户单击锚标记后立即从 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>
scrollRestoration 文档(检查它以获取有关 scrollRestoration 兼容性的信息)
推荐阅读
- python - 使用python selenium键入文本后如何从搜索建议中获取值?
- scala - 为日期创建和使用 Spark-Hive UDF
- angular - Angular 从 Spring Boot 获取异常文本
- r - 无法在 Windows 上安装 TinyTex - 访问被拒绝
- matlab - 如何在线部署 exe 文件或桌面应用程序
- polygon - 计算不重叠多边形的面积
- javascript - 无法使用 javascript 列出 azure datalake 的文件系统
- ios - 协助区分 URL 和 Tableview 数据
- sql - 如何计算表列GoogleSQL Bigquery中单词的频率
- r - 如何根据单独数据框中两列的结果在数据框中创建新列?