2012-07-16 44 views
3

在我的Rails應用程序中,我試圖構建一個簡單的常見問題解答頁面,其中有一個側邊欄,當您單擊某個主題時,它會轉到該問題。如何將HTML ID鏈接與Bootstrap導航欄標題一起使用?

所以一張我在側邊欄的代碼如下所示:

<li><a href="#work">How does it work?</a></li> 

然後,我有一個id =「工作」匹配H2。

當我對它進行測試時,它會保持超調,因爲它顯示的是從頁面頂部開始的內容,它由Bootstrap中的導航欄隱藏。補救這個的最好方法是什麼?

回答

4

有同樣的問題。這是我想出來的:

// listen for click events originating from elements with href starting with # 
$('body').on('click.scroll-adjust', '[href^="#"]', function (e) { 
    var $nav 

    // make sure navigation hasn't already been prevented 
    if (e && e.isDefaultPrevented()) return 

    // get a reference to the offending navbar 
    $nav = $('div.navbar') 

    // check if the navbar is fixed 
    if ($nav.css('position') !== "fixed") return 

    // listen for when the browser performs the scroll 
    $(window).one('scroll', function() { 
    // scroll the window up by the height of the navbar 
    window.scrollBy(0, -$nav.height()) 
    }); 

}); 
+0

如果我有一個自定義的固定導航欄,我該如何去做這件事? +1 – jamespick 2013-12-19 03:30:33

1

我修正了純CSS/HTML標記 - 這可能會或可能不會爲您工作,具體取決於您的結構。

首先,每次我在我的導航欄引用元素是一個div,因爲我的網頁被分成幾個部分,並且每個DAV具有類container所以頁面結構是:

<body> 
<div class="navbar navbar-fixed-top"> 
    <div class="navbar-inner"> 
    <div class="container"> 
     <ul class="nav"> 
     <li class="active"><a href="#one">one</a></li> 
     <li><a href="#two">two</a></li> 
     <li><a href="#three">three</a></li> 
     <li><a href="#four">four</a></li> 
     <li><a href="#five">five</a></li> 
     </ul> 
    </div> 
    </div> 
</div> 

<div class="container" id="one"> 
    <h1>One</h1> 
</div> 

... 

<div class="container" id="five"> 
    <h1>Five</h1> 
</div> 

的文檔建議您將身體至少填充40px以補償導航欄,這很好 - 但它只會在頁面位於頂部時將內容向下推。我發現,正如你所做的那樣,從靜態導航欄到頁面#錨點的任何鏈接都過高。

我的解決辦法是墊每一個錨定元素的頂部,所以我加入以下CSS到我的網頁CSS(標準引導和響應樣式之間的負載):

.container { 
    padding-top: 60px; 
} 

這顯然增加之間的空間我的頁面上的每個部分,但這在我的佈局中實際上很有用。

值得注意的是,因爲頂部還有這個填充,所以不需要在<body>標籤的頂部應用填充。