JQuery preventDefault()但仍然将片段路径添加到URL而不导航到片段

Eva*_*nss 4 jquery fragment-identifier preventdefault

我的问题类似于这个,但没有一个答案解决了我的问题: 使用JQuery preventDefault(),但仍然添加URL的路径

当用户单击片段链接时,我需要删除跳转到片段的默认行为,但仍然将片段添加到URL.此代码(取自链接)将触发动画,然后将片段添加到URL.然而,片段然后导航到,我的情况下我的网站.

$("#login_link").click(function (e) {
    e.preventDefault();
    $("#login").animate({ 'margin-top': 0 }, 600, 'linear', function(){  window.location.hash =     $(this).attr('href'); });

});
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 8

通过更新散列通过location.href,浏览器自动导航到指针.e.preventDefault()只取消事件的默认行为,它并不会影响其他哈希变化的方法,即使他们是来自同一个事件侦听器中调用.

您可以使用history.replaceStatehistory.pushState更改哈希而不跳转:

// Replaces the current history entry
history.replaceState(null, '', '#newhash');
Run Code Online (Sandbox Code Playgroud)