如何在不导致页面滚动的情况下删除位置哈希?

Dav*_*ing 76 javascript jquery fragment-identifier

是否有可能删除哈希window.location而不会导致页面跳转到顶部?我需要能够修改哈希而不会引起任何跳转.

我有这个:

$('<a href="#123">').text('link').click(function(e) {
  e.preventDefault();
  window.location.hash = this.hash;
}).appendTo('body');

$('<a href="#">').text('unlink').click(function(e) {
  e.preventDefault();
  window.location.hash = '';
}).appendTo('body');
Run Code Online (Sandbox Code Playgroud)

在这里查看实例:http://jsbin.com/asobi

当用户单击" 链接 "时,修改的哈希标记没有任何页面跳转,因此工作正常.

但是当用户点击" 取消链接 "时,删除了has标记,页面滚动跳转到顶部.我需要删除没有这种副作用的哈希.

scu*_*ffe 95

我相信如果你只是输入一个虚拟哈希它将不会滚动,因为没有匹配滚动到.

<a href="#A4J2S9F7">No jumping</a>
Run Code Online (Sandbox Code Playgroud)

要么

<a href="#_">No jumping</a>
Run Code Online (Sandbox Code Playgroud)

"#"本身相当于"_top"因此导致滚动到页面的顶部

  • 我用`window.location.hash ="";` (19认同)
  • 不是最佳,但足够好.我使用'#/'得到了相同的结果. (11认同)

neo*_*kio 36

我在几个网站上使用以下内容,NO PAGE JUMPS!

HTML5友好浏览器的干净地址栏,以及旧版浏览器的#.

$('#logo a').click(function(e){
    window.location.hash = ''; // for older browsers, leaves a # behind
    history.pushState('', document.title, window.location.pathname); // nice and clean
    e.preventDefault(); // no page reload
});
Run Code Online (Sandbox Code Playgroud)

  • `history.replaceState`可能更好,因为后退将返回到最后一个*valid*URL. (12认同)

olo*_*ney 18

window.location的hash属性在很多方面都是愚蠢的.这是其中之一; 另一个是具有不同的get和set值:

window.location.hash = "hello";  // url now reads *.com#hello
alert(window.location.hash);   // shows "#hello", which is NOT what I set.
window.location.hash = window.location.hash; // url now reads *.com##hello
Run Code Online (Sandbox Code Playgroud)

请注意,将哈希属性设置为''也会删除哈希标记; 这是重定向页面的内容.要将url的哈希部分的值设置为'',留下哈希标记,因此不刷新,请写下:

window.location.href = window.location.href.replace(/#.*$/, '#');
Run Code Online (Sandbox Code Playgroud)

一旦设置而没有刷新页面,就无法完全删除哈希标记.

2012年更新:

正如Blazemonger和thinkdj所指出的,技术已经有所改善.有些浏览器允许您清除该主题标签,但有些浏览器不允许.要支持两者,请尝试以下方法:

if ( window.history && window.history.pushState ) { 
    window.history.pushState('', '', window.location.pathname) 
} else { 
    window.location.href = window.location.href.replace(/#.*$/, '#'); 
}
Run Code Online (Sandbox Code Playgroud)

  • 不对.支持`window.history`的浏览器可以让你做到这一点. (2认同)