5

我正嘗試使用CSS Bootstrap affixlist-group菜單創建粘性菜單。如何使用css bootstrap list-group with affix在列中創建粘性菜單?

我設法讓大部分工作,除了用戶滾動時。

當用戶向下滾動時,菜單似乎佔據整個頁面。

我試圖用這樣的

<div class="container"> 
    <div class="row"> 
     <div class="col-md-3" id="leftCol"> 

      <div data-spy="affix"> 

       <div class="list-group list-group-root well"> 
        <a class="list-group-item" href="#introduction">Introduction</a> 
        <a class="list-group-item" href="#features">Features</a> 
        <a class="list-group-item" href="#dependencies">Dependencies</a> 
       </div> 

      </div> 

     </div> 
     <div class="col-md-9" id="mainCol"> 

      Some long text for the body along with some tables. 

     </div> 
    </div> 
</div> 

但數據的屬性並沒有使菜單堅持通過數據屬性

設置它!它只是保持在頂部。

所以我試圖用JS來獲得我創建jsFiddle這樣

$(function(){ 

    $('#leftCol').affix({ 
     offset: { 
     top: 100, 
     bottom: function() { 
      return (this.bottom = $('.footer').outerHeight(true)) 
     } 
     } 
    }); 


}); 

所做的工作向你展示當前行爲。

我該如何解決這個問題affix所以當用戶向下滾動菜單時保持相同的形狀?

回答

1

首先,你應該使用數據屬性或JS。我想更新你的jsFiddle。 ID =「leftCol」的位置被改變:加入

<div class="col-md-3" > 

     <div id="leftCol"> 

       ... 

     </div> 

    </div> 

和風格:

#leftCol { 
    width: 220px; 
} 

此外,你應該添加媒體查詢刪除從移動視圖貼上。

+1

我刪除數據的屬性和使用的唯一JS。 –

+0

這就是我所做的。但爲什麼我必須將修復或最大寬度添加到容器?它是用一個'col-md-3'類包裝的,它應該控制菜單的寬度以適應任何設計。 –

+0

寬度的目的是什麼:200px?它已經在col-md-3中。此外,我仍然有與您鏈接的JSFIddle相同的問題 – Mese

1

爲「不可接受」的解決辦法,我的菜單的最大寬度設置爲250px像這樣

.list-group.list-group-root { 
    padding: 0; 
    max-width: 250px; 
} 

我不知道如何得到它不添加max-with最大使用應該被定義工作由父母。在這種情況下class="col-md-3"

修訂

JavaScript來救援!

我加了下面的JS代碼來解決這個問題。

它基本上調整菜單每次affix.bs.affix事件立即=>此事件發射

$(document).on('affix.bs.affix', '#docs-menu', function() { 
    $(this).width($(this).width()); 
}); 

docs

affix.bs.affix的元素已 被貼上之前。

0

好吧,我相信我的大部分代碼工作像你想讓它。我的主要變化是在加入這個CSS:

#leftCol { 
    display: block; 
    height: auto; 
    padding: 0; 
    width: 100%; 
} 

.navbar-fixed-top-again { 
    position: static; 
    top: 60px; 
    z-index:1031; 
} 
.navbar-inner { 
    background: red; 
    padding: 5px; 
} 

.affix { 
    position: fixed !important; 
} 

,我改變了一些結構上的HTML:

<div class="container body-content"> 
    <div>made up content to allow the navigation to scroll more before it becomes sticky. This height will need to be set in the data-offset-top which is in the leftCol DIV just below this content. The same will apply if you need to set it for a footer offset.</div> 

    <!-- new nav section --> 
    <div class="col-md-3 navbar-fixed-top-again" id="leftCol" data-spy="affix" data-offset-top="80"> 
     <div class="navbar-inner"> 
      <div class="list-group list-group-root well"> 
      *the rest of your code* 
      </div> 
     </div> 
    </div> 
</div> 

現在主要的問題是具有可變高度粘性的導航菜單。如果你注意到當你在閱讀內容的下方滾動並隱藏起來。看起來它是possible to fix this using JavaScript (link to SO question)

繼承人的link to your updated Fiddle。希望有所幫助。