如何阻止带有哈希的 URL 跳转到锚点



我尝试了几乎所有人对类似问题的回答,但答案对我没有帮助。所以我会发布我的代码,然后解释我的问题的更多细节。

链接以查看代码和编辑器。
http://jsbin.com/nudavoseso/edit?html,js,output

正文内部.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 id="content1" class="content">
  <h1>One</h1>
  <p>Content goes here</p>
</div>
<div id="content2" class="content">
  <h1>Two</h1>
  <p>Content goes here</p>
</div>
<div id="content3" class="content">
  <h1>Three</h1>
  <p>Content goes here</p>
</div>

以及文件中.js代码。

function tabs() {
  $(".content").hide();
  if (location.hash !== "") {
    $(location.hash).fadeIn();
    $('.tabs ul li:has(a[href="' + location.hash + '"])').addClass("active");
  } else {
    $(".tabs ul li").first().addClass("active");
    $('.tabs').next().css("display", "block");
  }
}
tabs();
$(".tabs ul li").click(function() {
  $(".tabs ul li").removeAttr("class");
  $(this).addClass("active");
  $(".content").hide();
  var activeTab = $(this).find("a").attr("href");
  location.hash = activeTab;
  $(activeTab).fadeIn();
  return false;
});

如果您查看下面的示例 url,一切都很好。
http://output.jsbin.com/nudavoseso

问题
所在如果您转到上面带有主题 #content1 标签的相同 url,最后它会跳转到锚点(#content1),我不希望页面跳转到锚点。我希望页面始终从顶部开始。仅当它是指向 URL 的直接链接时,才会发生这种情况。
http://output.jsbin.com/nudavoseso#content1

如果您愿意对用户体验造成轻微打击,您可以检测哈希何时存在,只需重新加载没有哈希的页面:

if (location.hash) {
  window.location = location.href.replace(location.hash, '');
}

修复

.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

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

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

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

最新更新