2016-03-27 82 views
0

我正在學習引導程序,我希望我的自定義水平導航欄在頁面頂部一旦粘到頁面上(如this)。 我試圖添加一個詞綴類到我的CSS以及一段JS代碼,但這不起作用。什麼是問題? 見https://jsfiddle.net/bs7bdpmh/問題構建固定的側邊欄

HTML

<div id="nav" class="container-fluid"> 
    <nav class="navbar-classic"> 
    <li><a href="index.html" class="active">Who are we? </a> 
     <ul class="dropdown"> 
     <li><a href="#">Sub 1</a></li> 
     <li><a href="#">Sub 2</a></li> 
     </ul> 
    </li> 
    <li><a href="#">Services Services Services</a> 
    </li> 
    <li><a href="#">Products Products Products</a> 
    </li> 
    </nav> 

CSS

#nav.affix { 
    position: fixed; 
    top: 0; 
    width: 100%; 
    height: 70px; 
    background: #fff; 
    z-index:10; 
} 

JS

$('#nav').affix({ 
     offset: { 
     top: $('header').height() 
     } 
}); 
+0

當你添加引導JavaScript和jQuery依賴關係時,你的小提琴代碼工作。 – str

回答

0

你的意思是這樣的嗎?

See this fiddle

JS:

$(window).scroll(function(){ 
    scrollTop = $(window).scrollTop(); 
    if(scrollTop > 50){ 
    $('#nav').addClass('affix'); 
    }else{ 
    $('#nav').removeClass('affix'); 
    } 
}); 

當然,它並不完美,我讓你適應的CSS代碼和HTML結構;)

+0

謝謝!你知道爲什麼使用修正菜單時,菜單項會移到視口的最右側,並將徽標移到最左側? (我希望它們保持在與初始菜單相同的容器寬度內) – Greg

+0

如果您想要使用與非固定菜單相同的寬度,您必須指定它 檢查此#nav.affix;的寬度) –

0

如果使用正常引導的解決方案容易

<style> 
    /* Note: Try to remove the following lines to see the effect of CSS positioning */ 
    .affix { 
     top: 0; 
     width: 100%; 
    } 

    .affix + .container-fluid { 
     padding-top: 70px; 
    } 
    </style> 
</head> 
<body> 

<div class="container-fluid" style="background-color:#F44336;color:#fff;height:200px;"> 
    <h1>Bootstrap Affix Example</h1> 
    <h3>Fixed (sticky) navbar on scroll</h3> 
    <p>Scroll this page to see how the navbar behaves with data-spy="affix".</p> 
    <p>The navbar is attached to the top of the page after you have scrolled a specified amount of pixels.</p> 
</div> 

<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197"> 
    <ul class="nav navbar-nav"> 
    <li class="active"><a href="#">Basic Topnav</a></li> 
    <li><a href="#">Page 1</a></li> 
    <li><a href="#">Page 2</a></li> 
    <li><a href="#">Page 3</a></li> 
    </ul> 
</nav> 

如果你想改變導航當你滾動到底部只是使用類似的東西吧:

$(window).scroll(function(){ 
     if($(window).scrollTop() + $(window).height() == $(document).height()) 
     { 
     $('#nav').addClass('affix'); 
     } 

});