[英]How to stop html page from jumping when anchor is clicked, but still go to the url in the href?
[英]How to stop URL with hash from jumping to anchor?
我已经尝试了几乎每个人对类似问题的回答,但这些答案对我没有帮助。 所以我会发布我的代码,然后解释我的问题的更多细节。
链接以查看和编辑器中的代码。
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) ,我不希望页面跳转到锚点。 我希望页面总是从顶部开始。 这只发生在它是指向 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;
});
没有任何哈希值的 URL。
http://output.jsbin.com/tojeja
带有不跳转到锚点的主题标签的 URL。
http://output.jsbin.com/tojeja#content1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.