我已经尝试了几乎每个人对类似问题的答案,但答案对我没有帮助。因此,我将发布我的代码,然后解释我的问题的更多细节。
用于在编辑器中查看代码的链接。
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/