![](/img/trans.png)
[英]Twitter's Bootstrap fixed-to-top navbar on scroll with in-page anchor links bouncing
[英]In-page anchors not working properly in combination with “scroll-then-fix” JS navbar code
我使用這個漂亮的小JavaScript來使我的導航欄(通常從頂部向下坐230px)一旦頁面向下滾動230 px就會粘到頁面頂部。 然后它給“nav”元素一個“固定”位置。
$(document).ready(function() { $(window).bind('scroll', function() { if ($(window).scrollTop() > 230) { $('nav').addClass('fixed'); } else { $('nav').removeClass('fixed'); } }); });
nav { width: 90%; display: flex; justify-content: center; max-width: 1400px; height: 85px; background-color: rgba(249, 241, 228, 1); margin: auto; border-top-left-radius: 0em; border-top-right-radius: 0em; border-bottom-left-radius: 2em; border-bottom-right-radius: 2em; } .fixed { position: fixed; border-top: 0; top: 0; margin: auto; left: 0; right: 0; z-index: 4; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav> <ul> <li><a href="#one">One</a></li> <li><a href="#two">Two</a></li> <li><a href="#three">Three</a></li> <li><a href="#four">Four</a></li> </ul> </nav>
現在,問題是:我已經在頁面中定位了相應的錨點目標,並為它們提供了一些“填充頂部”來解釋固定的導航欄(大約90px),這樣當頁面跳轉時它們不會消失在欄后面點擊后給他們。
.anchor {
padding-top: 90px;
}
<a class="anchor" id="three">
由於導航欄已固定在頂部,因此工作正常。 但是如果你在導航欄仍然處於其原始頁面中間位置時點擊一個鏈接(例如用戶將會進行的第一次點擊),它只會忽略我給錨定目標的偏移並跳轉到錨定目標的奇怪位置隱藏在導航欄后面(甚至沒有與頁面頂部對齊)!
如果我然后再次單擊該鏈接(現在位於頁面頂部的固定欄中),它會自行更正並顯示我想要的頁面。 但是,第一次點擊總是錯過 - 我無法弄清楚為什么! 請幫忙
編輯:在這里工作演示: http ://www.myway.de/husow/problem/problem.html
1st使用class="space"
為您的第一個div添加一個新的類名稱spacebody
<nav>
...
</nav>
<div class="space spacebody">
</div>
第二個JS使用以下應該解決你的問題:
$(document).ready(function() {
$(window).bind('scroll', function() {
if ($(window).scrollTop() > 230) {
$('nav').addClass('fixed');
$('.spacebody').css('margin-top', '85px');
} else {
$('nav').removeClass('fixed');
$('.spacebody').css('margin-top', '0px');
}
});
});
原因?
因為當導航沒有固定時,它的高度為85px,當你向下滾動它沒有高度為0高度時。 然后下面的所有內容都會向上移動85px,導致你低於ONE
或TWO
等目標。不是你錯過了第一次點擊,當導航沒有修復時,點擊你將向下滾動85px。 如果您滾動到頂部並單擊,您將再次錯過。
如果您使用background-color: transparent;
更改nav
CSS,則可以輕松看到此內容background-color: transparent;
使用上面的代碼時,應該修復它,當導航變為固定時,將margin-top添加為下方的div為85px,以便它們與您單擊時保持相同的高度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.