2013-12-19 107 views
11

所以在我的網站上,我在網站的最頂端有一個靜態標頭 - 它並不固定在視口的頂部。但是,我想要做的是一旦用戶滾動過這個div的底部,就會出現一個固定的導航欄。我的代碼幾乎可以工作,但只觸發div頂部的偏移量,這是頁面的頂部。這裏是我的代碼:滾動元素底部時觸發事件?

$("#header-2").hide(); // hide the fixed navbar initially 

var topofDiv = $("#header-container").offset().top; //gets offset of header 
$(window).scroll(function(){ 
    if($(window).scrollTop() > topofDiv){ 
     $("#header-2").show(); 
    } 
    else{ 
     $("#header-2").hide(); 
    } 
}); 

同樣,我需要觸發顯示過去的#header-container底部的導航欄固定,一旦用戶滾動,並不像它的頂部現在。幫幫我?

+2

到它的偏移只需添加元素的高度。 – undefined

+0

要獲得底部只需將#header-container的高度添加到topfoDiv .. – synapze

+0

查看[headhesive.js](https://github.com/markgoodyear/headhesive.js/)和[waypoints.js](http ://imakewebthings.com/waypoints/) – xr280xr

回答

24

我認爲,如果你添加DIV到頂部的高度偏移,你會得到的行爲你想

$("#header-2").hide(); // hide the fixed navbar initially 

var topofDiv = $("#header-container").offset().top; //gets offset of header 
var height = $("#header-container").outerHeight(); //gets height of header 

$(window).scroll(function(){ 
    if($(window).scrollTop() > (topofDiv + height)){ 
     $("#header-2").show(); 
    } 
    else{ 
     $("#header-2").hide(); 
    } 
}); 
+0

這樣做。謝謝! –