javascript - 如何阻止带有哈希值的URL跳转到 anchor ?

标签 javascript jquery tabs anchor hashtag

我已经尝试了几乎每个人对类似问题的答案,但答案对我没有帮助。因此,我将发布我的代码,然后解释我的问题的更多细节。

用于在编辑器中查看代码的链接。
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;
});

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

问题
如果您转到上面带有 #content1 标签的同一网址,它跳转到 anchor (#content1),我不希望页面跳转到 anchor 。我希望页面始终从顶部开始。仅当直接链接到 URL 时才会发生这种情况。
http://output.jsbin.com/nudavoseso#content1

最佳答案

如果您愿意稍微影响用户体验,您可以检测哈希是否存在,然后只需重新加载没有哈希的页面即可:

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

关于javascript - 如何阻止带有哈希值的URL跳转到 anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30007717/

相关文章:

javascript - 如何替换列表中特定索引处的元素

javascript - 使用绝对路径加载json文件

javascript - 使用脚本更改网站的元素?

android - 留在屏幕上的 TabLayout 原始 fragment

javascript - compass/咖啡可以做到这一点吗?另一种方法?

javascript - 如何生成 Twitter Bootstrap 模式但保持隐藏

javascript - 如何通过单击另一个链接来打开切换功能

javascript - 使用 li 和 dl 与 jquery 进行级联下拉菜单

javascript - fakewaffle响应选项卡屏幕问题

java - 如何更改 Activity 中选项卡布局的位置?