2017-01-15 33 views
0

我一直在開發一個項目一段時間,其中我創建了一個導航欄,它是static,直到滾動到,此時它變成fixed到頂部屏幕。這個導航欄效果很好,但是當它的粘性,它下面的元素向上跳躍,以填補其留下的空白。我怎樣才能使它所以這些元素保持不動,一旦導航欄的position變化?我已經在下面列出了相關的代碼,以防萬一需要。當我粘貼導航欄時,如何保持我的其他屬性靜止

HTML:

<div id="navbar"><ul> 
    <li id="activePage"><a href="">Home</a></li> 
    <li><a href="">About</a></li> 
    <li><a href="">Upcoming events </a><li> 
    <li><a href="">Contact Us</a></li> 
    <li><a href="">Contribute</a></li> 
</ul></div> 

CSS:

#navbar { 
    background-color: white; 
    z-index: 1; 
} 

#navbar ul { 
    list-style-type: none; 
    margin: 0; 
    padding: 0; 
    overflow: hidden; 
    text-align: center; 
    width: 100%; 
} 

#navbar li { 
    text-align: center; 
    display: inline; 
} 

#navbar ul #activePage a { 
    color: #cec8c8; 
} 

#navbar li a { 
    color: black; 
    padding: 14px 35px; 
    text-decoration: none; 
    font-family: 'Roboto Slab'; 
    font-size: 25px; 
    text-align: center; 
} 

JS:

$(document).ready(function(){ 
    var elementPosition = $('#navbar').offset(); 
    $(window).scroll(function() { 
     if ($(window).scrollTop() > elementPosition.top) { 
      $('#navbar').css('position', 'fixed').css({'top':'0','left':'0','right':'0'); 
     } else { 
      $('#navbar').css('position', 'static'); 
}})}); 

回答

0

的問題,因爲你已經在暗示,是隻要你改變導航欄位置固定的,你從頁面流和下方的頁面內容的其餘部分中取出發送「向上」填補這一空白。

如果你有一個div已經包裹導航欄下面的頁面內容,你的if語句中添加這一點,它會在你的導航欄從頁面流中去除,同時增加保證金。

// Added margin top to the content's wrapper to account for the navbar being taken out of the flow of the page. 
$('***Main Content Wrapper Class/ID***').css('margin-top', '***[[THE HEIGHT OF THE NAV]]***'); 
// Once your scroll top is back to where the navbar is static again 
    $('***Main Content Wrapper Class/ID***').css('margin-top', '0'); 

OR


// Or you can add a class and remove a class with the margin-top style within 
    $('Main Content Wrapper Class/ID').addClass('scrolledNav'); 


    // Once your scroll top is back to where the navbar is static again 
     $('Main Content Wrapper Class/ID').removeClass('scrolledNav'); 

CSS:

.scrolledNav { 
     margin-top: [navbar height]px 
    } 
相關問題