[英]Twitter's Bootstrap fixed-to-top navbar on scroll with in-page anchor links bouncing
我有一個帶有頂部水平導航欄的網頁-更確切地說是Twitter的Bootstrap固定頂部導航欄-底部固定的位置(實際上CSS並沒有真正固定它;請參見下面的JavaScript),因此導航欄將首先是在頁面底部可見,然后在滾動時顯示在頁面頂部( position: fixed; top: 0
)。
我的導航鏈接設置了定位標記,以將查看器帶到頁面正文中的各個位置。 不幸的是,有時這會使用戶走得太遠(特別是如果用戶位於頁面頂部並且導航欄尚未固定)。
看一下我的HTML結構:
<div id="landing"></div>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#landing">Home</a></li>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
</ul>
</div>
</div>
</nav>
<div id="section1"></div>
<div id="section2"></div>
<div id="section3"></div>
我正在使用以下JavaScript,以確保向下滾動后導航欄停留在頁面頂部:
function init() {
nh = 50; // navbar height
sh = $(window).height();
ih = sh-nh;
$("#landing").css('height', ih+'px');
}
function navbarState() {
if ($(window).scrollTop() > ih) {
$('.navbar').addClass('navbar-fixed-top');
} else {
$('.navbar').removeClass('navbar-fixed-top');
}
}
init();
navbarState();
$(window).on('load scroll resize orientationchange', function () {
init();
navbarState();
});
可以觀察到,反復按下第一根錨桿會產生彈跳效果。 我該如何預防?
我的目標是使導航滾動到適當的錨點,而不管用戶是否在目標網頁上。
為什么不同時使用navbar-fixed-bottom
?
看到這里: https : //jsfiddle.net/y7soL4ej/
我將提到的類作為默認添加到nav
。 並修改了小事:
的CSS
html, body, div#landing {
height: 100%
}
section, [id*=section] {
padding-top: 52px;
}
JS
function init() {
nh = 50 + 2; // navbar height + 2x border width (top + bottom)
sh = $(window).height();
ih = sh-nh;
//$("#landing").css('height', ih+'px');
}
function navbarState() {
if ($(window).scrollTop() > ih) {
$('.navbar').removeClass('navbar-fixed-bottom').addClass('navbar-fixed-top');
} else {
$('.navbar').removeClass('navbar-fixed-top').addClass('navbar-fixed-bottom');
}
}
init();
navbarState();
$(window).on('load scroll resize orientationchange', function () {
init();
navbarState();
});
跳動的行為:在您的示例中,導航欄位於底部時,它是dom流的一部分-它按其高度將着陸 div和section1 div分開。 單擊瀏覽器后,瀏覽器將跳轉到該位置,然后將導航欄設置為固定在頂部-不再是流的一部分(兩個div不再被其分隔)。 因此, 部分 div相應地向上移動到着陸 div,以縮小間隙。 因此,再次單擊同一部分錨點將導致額外的跳轉,因為由於着陸 div從position:static
到position:fixed
,該部分被重新定位。
這是我建議使用navbar-fixed-bottom
的另一個原因。
更新資料
新提琴: https : //jsfiddle.net/y7soL4ej/2/
我從HTML和JS中刪除了.navbar-fixed-bottom
,因為導航欄不應從底部跳到頂部。 為了使其平滑並避免前面提到的跳動行為,我必須將其設置為絕對位置。
需要添加一些CSS :
div#landing {
padding-bottom: 72px;
margin-bottom: -72px;
}
nav.navbar {
position: absolute;
left: 0; right: 0;
}
nav.navbar.navbar-fixed-top {
position: fixed;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.