当页面从服务工作者那里收到消息时,我试图刷新它,当看到新的内容时(这就是页面刷新时锚应该跳到的内容)。
所以想象一下我有这些:
var url = 'http://example.com/home.htm';
var anchor = '#comment-45';
带有那个url的页面已经加载了。我想重新加载页面,然后跳到#注释-45。
所有这些都不起作用:
这不会重新加载页面,只是尝试跳转到不存在的锚点:
window.location = url+anchor;
更改以更正URL和重新加载,但不会跳转到新锚点:
window.location.hash = anchor;
window.location.reload(true);
或
window.location.href = url+anchor;
window.location.reload(true);
将页面重新加载到基本URL,但不会更改锚点:
window.location = url;
window.location.hash = anchor;
发布于 2020-01-21 17:25:00
假设你添加了
<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);
将滚动到在重新加载时的最后一个锚。
发布于 2020-01-21 17:25:48
在我的经验中,有许多情况不会触发浏览器滚动到锚。我发现了一个后遗症,它在URL中查找散列/片段,并使用JS在加载时滚动到它,使其更可靠。如果您可以使用您概述的方法之一添加锚并重新加载,您应该能够使用它来处理滚动:
const scrollTo = el => {
if (el) {
const top = window.scrollY + el.getBoundingClientRect().top
window.scrollTo({ top: top, behavior: "smooth" })
}
}
// wrap in a domReady type callback if needed
scrollTo(document.querySelector(window.location.hash))
https://stackoverflow.com/questions/59846207
复制相似问题