2014-01-30 16 views
1

我正在使用Twitter Bootstrap 3.0,使用ScrollSpy插件在我向下滾動時激活我的「導航」鏈接。現在我想要自動更新地址欄中的URL(使用window.history.pushstate)來響應ScrollSpy事件「activate.bs.scrollspy」。在Bootstrap中,如何識別「活動」導航元素?

如何識別ScrollSpy爲我激活的「nav」元素?

我的代碼看起來像這樣。

<body data-spy="scroll" data-target="#primarynavbar"> 
    <div id="primarynavbar" class="navbar navbar-inverse navbar-fixed-top" role="navigation"> 
... 
... 
     <li><a href="#contact">Contact Us</a></li> 
... 
... 
    <div id="contact" /> 
... 
... 
    <script> 
     $('#primarynavbar').on('activate.bs.scrollspy', function() { 
      window.history.pushstate('http://abcd.com#contact') 
     }); 
    </script> 
... 

回答

3

我會假設你可以尋找活動類,並獲得子錨點href屬性:

$('#primarynavbar').on('activate.bs.scrollspy', function() { 
    var hash = $(this).find("li.active a").attr("href"); 
    window.history.pushstate('http://abcd.com' + hash); 
}); 
+0

賓果!這工作得很好。 – Boinst

+0

工程就像一個魅力。如果你有一個嵌套的菜單,你會想使用當前的子菜單項。下面是你的選擇器的一個簡化版本:'var hash = $(this).find(「li.active:last a」)。attr(「href」);'' – kernel