![](/img/trans.png)
[英]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.