7

我正在尝试更新哈希然后重新加载页面。

$('a[name="' + fragment + '"]').remove(); //don't jump before window reloads
window.location.hash = fragment;
window.location.reload(true);

重新加载后窗口不会跳转到锚标记。我该如何解决?

4

3 回答 3

2

如果您正在重新加载页面,这在 jQuery 中实现起来相当简单。只需window.location.hash在加载页面时检查属性。

$(document).ready( function( ) {
    if( window.location.hash ) { // just in case there is no hash
        $(document.body).animate({
            'scrollTop':   $( window.location.hash ).offset().top
        }, 2000);
    }
});

唯一需要注意的是,您的哈希值与您滚动到的元素的 id 匹配。

演示在这里

于 2012-12-19T12:19:26.787 回答
1

MOZILLA 开发者网络建议使用replace

function reloadPageWithHash() {
  var initialPage = window.location.pathname;
  window.location.replace('http://example.com/#' + initialPage);
} 
于 2012-12-19T12:09:02.970 回答
0

@Tim S. my intention is absolutely not to steal your thunder but your very low key comment above is in my opinion the optimal solution to this question as it is simple, clean and tests successfully across a variety of browsers. I am therefore creating an answer of it on your behalf:

window.location.href = url#anchor

(where url can be the current page - or a different one as desired)

于 2016-05-03T22:35:10.313 回答