我正在尝试更新哈希然后重新加载页面。
$('a[name="' + fragment + '"]').remove(); //don't jump before window reloads
window.location.hash = fragment;
window.location.reload(true);
重新加载后窗口不会跳转到锚标记。我该如何解决?
我正在尝试更新哈希然后重新加载页面。
$('a[name="' + fragment + '"]').remove(); //don't jump before window reloads
window.location.hash = fragment;
window.location.reload(true);
重新加载后窗口不会跳转到锚标记。我该如何解决?
如果您正在重新加载页面,这在 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 匹配。
演示在这里
MOZILLA 开发者网络建议使用replace
:
function reloadPageWithHash() {
var initialPage = window.location.pathname;
window.location.replace('http://example.com/#' + initialPage);
}
@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)