Javascript 在window.location.reload之后转到锚点链接
我正在尝试更新哈希,然后重新加载页面Javascript 在window.location.reload之后转到锚点链接,javascript,anchor,Javascript,Anchor,我正在尝试更新哈希,然后重新加载页面 $('a[name="' + fragment + '"]').remove(); //don't jump before window reloads window.location.hash = fragment; window.location.reload(true); 重新加载后,窗口不会跳转到锚定标记。如何修复它?建议使用replace: function reloadPageWithHash() { var initialPage = w
$('a[name="' + fragment + '"]').remove(); //don't jump before window reloads
window.location.hash = fragment;
window.location.reload(true);
重新加载后,窗口不会跳转到锚定标记。如何修复它?建议使用replace
:
function reloadPageWithHash() {
var initialPage = window.location.pathname;
window.location.replace('http://example.com/#' + initialPage);
}
如果要重新加载页面,在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相匹配
Demo@Tim S。我的目的绝对不是想抢走你的风头,但我认为你上面的非常低调的评论是解决这个问题的最佳方法,因为它简单、清晰,并且可以在各种浏览器上成功地进行测试。因此,我代表您对此做出回答:
window.location.href = url#anchor
(其中url可以是当前页面,也可以是需要的另一个页面)为什么要使用散列,然后重新加载页面?我认为您最好更改
href
属性:window.location.href=url+'#您的散列'
的想法是重新加载页面,然后将屏幕跳转到页面上的特定位置。如果url/锚相同,则不会重新加载页面。