引用页面部分的锚链接不适用于浏览器刷新、后退和前进

anchor links referring to the page sections not working on browser refresh, back and forward

我制作了一个 html 页面,页面内有链接。

<div>
<a href="#first">first</a>
<a href="#second">second</a>
<div id="first">First div</div>
<div id="second">Second div</div>
</div>

但此代码不适用于页面刷新和浏览器后退和前进按钮。 有谁知道如何解决这个问题。我不是在寻找 html5 的历史记录 api 和 jquery 的历史记录插件。想要以其基本格式创建它。

好的,经过多次尝试,我已经找到了如何去做。现在这处理了我的目的,所以我继续这个解决方案。

$(window).on('hashchange', function () 
{
    var top = $(window.location.hash).offset().top;
    $(window).scrollTop(top);
});

这适用于前进和后退按钮。对于刷新,我们也需要做同样的事情。从哈希中获取元素并手动滚动到该元素。