2014-04-25 45 views
0

當我滾動並實現它時,我一直在嘗試使導航欄位於頂部。唯一的問題是,當導航欄過渡到固定位置時,我的內容會啓動。導航欄內容在位置更改爲固定滾動時跳過

下面是這種行爲的一個例子:http://jsfiddle.net/7HHa5/4/

的JavaScript

window.onscroll = changePos; 

function changePos() { 
    var header = document.getElementById("header"); 
    if (window.pageYOffset > 70) { 
     header.style.position = "absolute"; 
     header.style.top = pageYOffset + "px"; 
    } else { 
     header.style.position = ""; 
     header.style.top = ""; 
    } 
} 

我使用的引導和jQuery。

我該如何避免這種行爲?

+0

有與沒有使用'位置的主要問題:fixed'? – potashin

回答

0

當您將標頭設置爲position: absolute時,它會留下一個由內容填充的空白空間。您需要將保證金添加到內容的頂部時,頭會變成固定,就像這樣:

window.onscroll = changePos; 

function changePos() { 
    var header = document.getElementById("header"); 
    var content = document.getElementById("content"); 
    if (window.pageYOffset > 70) { 
     header.style.position = "absolute"; 
     header.style.top = pageYOffset + "px"; 
     content.style.marginTop = '55px' 
    } else { 
     header.style.position = ""; 
     header.style.top = ""; 
     content.style.marginTop = '0' 
    } 
} 

爲例見http://jsfiddle.net/2EhLs/1/

但是,有一個更好的方法。

由於您已經在使用Bootstrap,因此您應該考慮使用內置的Affix功能。

最好的例子就是從another questionthis one

$('#nav-wrapper').height($("#nav").height()); 

$('#nav').affix({ 
    offset: { top: $('#nav').offset().top } 
}); 
相關問題