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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2295845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:39:25  来源:igfitidea点击:

How can I remove the location hash without causing the page to scroll?

javascriptjqueryfragment-identifier

提问by David Hellsing

Is it possible to remove the hash from window.locationwithout causing the page to jump-scroll to the top? I need to be able to modify the hash without causing any jumps.

是否可以在window.location不导致页面跳转到顶部的情况下删除哈希?我需要能够在不引起任何跳转的情况下修改哈希。

I have this:

我有这个:

$('<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');

See live example here: http://jsbin.com/asobi

在此处查看现场示例:http: //jsbin.com/asobi

When the user clicks 'link' the hash tag is modified without any page jumps, so that's working fine.

当用户单击“链接”时,哈希标签被修改而没有任何页面跳转,因此工作正常。

But when the user clicks 'unlink' the has tag is removed and the page scroll-jumps to the top. I need to remove the hash without this side-effect.

但是当用户点击“取消链接”时,has 标签被删除,页面滚动跳转到顶部。我需要在没有这种副作用的情况下删除哈希。

回答by scunliffe

I believe if you just put in a dummy hash it won't scroll as there is no match to scroll to.

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

<a href="#A4J2S9F7">No jumping</a>

or

或者

<a href="#_">No jumping</a>

"#"by itself is equivalent to "_top"thus causes a scroll to the top of the page

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

回答by neokio

I use the following on a few sites, NO PAGE JUMPS!

我在几个网站上使用以下内容,没有页面跳转!

Nice clean address bar for HTML5 friendly browsers, and just a # for older browsers.

用于 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
});

回答by olooney

window.location's hash property is stupid in a couple of ways. This is one of them; the other is that is has different get and set values:

window.location 的 hash 属性在几个方面是愚蠢的。这是其中之一;另一个是具有不同的获取和设置值:

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

Note that setting the hash property to '' removes the hash mark too; that's what redirects the page. To set the value of the hash part of the url to '', leaving the hash mark and therefore not refreshing, write this:

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

window.location.href = window.location.href.replace(/#.*$/, '#');

There is no way to completely remove the hash mark once set without refreshing the page.

一旦设置了哈希标记,就无法在不刷新页面的情况下完全删除哈希标记。

UPDATE 2012:

2012 年更新:

As Blazemonger and thinkdj have pointed out, technology has improved. Some browsers do allow you to clear that hashtag, but some do not. To support both, try something like:

正如 Blazemonger 和 thinkdj 指出的那样,技术已经改进。有些浏览器确实允许您清除该主题标签,但有些则不允许。要支持两者,请尝试以下操作:

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

回答by Tomer Gal

This is an old post but I wanted to share my solution All the links in my project that being handled by JS are having href="#_js" attribute (or whatever name you want to use for that purposes only), and on page initialization I do:

这是一篇旧帖子,但我想分享我的解决方案我的项目中由 JS 处理的所有链接都具有 href="#_js" 属性(或您只想用于该目的的任何名称),以及页面初始化我愿意:

$('body').on('click.a[href="#_js"]', function() {
    return false;
});

That'll do the trick

这样就行了

回答by BGerrissen

Setting window.location.hash to empty or non-existing anchor name, will always force the page to jump to top. The only way to prevent this is to grab the scroll position of the window and set it to that position again after the hash change.

将 window.location.hash 设置为空或不存在的锚名称,将始终强制页面跳转到顶部。防止这种情况的唯一方法是获取窗口的滚动位置,并在哈希更改后再次将其设置为该位置。

This will also force a repaint of the page (cant avoid it), though since it's executed in a single js process, it won't jump up/down (theoretically).

这也将强制重新绘制页面(无法避免它),但由于它是在单个 js 进程中执行的,因此它不会向上/向下跳转(理论上)。

$('<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();
    var pos = $(window).scrollTop(); // get scroll position
    window.location.hash = '';
    $(window).scrollTop(pos); // set scroll position back
}).appendTo('body');

Hope this helps.

希望这可以帮助。

回答by Roman Nurik

Have you tried return false;in the event handler? jQuery does something special when you do that, similar to, but AFAIK more impactful, than e.preventDefault.

您是否return false;在事件处理程序中尝试过?当你这样做时,jQuery 会做一些特别的事情,类似于,但 AFAIK 比e.preventDefault.

回答by Tom Bartel

I'm not sure if this produces the desired outcome, give it a shot:

我不确定这是否会产生预期的结果,试一试:

$('<a href="#">').text('unlink').click(function(e) {
    e.preventDefault();
    var st = parseInt($(window).scrollTop())
    window.location.hash = '';
    $('html,body').css( { scrollTop: st });  
});

Basically save the scroll offset and restore it after assigning the empty hash.

基本上保存滚动偏移并在分配空哈希后恢复它。

回答by Shak Daniel

Hope this helps

希望这可以帮助

html

html

<div class="tabs">
  <ul>
    <li><a href="#content1">Tab 1</a></li>
    <li><a href="#content2">Tab 2</a></li>
    <li><a href="#content3">Tab 3</a></li>
  </ul>
</div>
<div class="content content1">
    <p>1. Content goes here</p>
</div>
<div class="content content2">
    <p>2. Content goes here</p>
</div>
<div class="content content3">
    <p>3. Content goes here</p>
</div>

js

js

function tabs(){
  $(".content").hide();

  if (location.hash !== "") {
    $('.tabs ul li:has(a[href="' + location.hash + '"])').addClass("active");
    var hash = window.location.hash.substr(1);
    var contentClass = "." + hash;
    $(contentClass).fadeIn();
  } else {
    $(".tabs ul li").first().addClass("active");
    $('.tabs').next().css("display", "block");
  }
}
tabs();

$(".tabs ul li").click(function(e) {
  $(".tabs ul li").removeAttr("class");
  $(this).addClass("active");
  $(".content").hide();
  var contentClass = "." + $(this).find("a").attr("href").substr(1);
  $(contentClass).fadeIn();
  window.location.hash = $(this).find("a").attr("href");
  e.preventDefault();
  return false;
});

URL without any hash.
http://output.jsbin.com/tojeja

没有任何哈希值的 URL。
http://output.jsbin.com/tojeja

URL with hashtag that does not jumping to anchor.
http://output.jsbin.com/tojeja#content1

带有不跳转到锚点的主题标签的 URL。
http://output.jsbin.com/tojeja#content1