Bootstrap 3 Scrollspy remove active state

天大地大妈咪最大 提交于 2019-12-23 10:09:36

问题


I have a site using Bootstrap with scrollspy and a fixed header. I have it working fine, but have run into a problem with scrollspy. There are a couple sections on the page that aren't part of the main navigation. When you're in these sections, the most recent 'active' link remains. Easiest to demonstrate the issue in a fiddle:

http://jsfiddle.net/eric1086/R7S9t/1/

<body data-spy="scroll" data-target=".main-nav">
<nav class="main-nav">
  <ul class="nav">
    <li><a href="#first">First</a></li>
    <li><a href="#second">Second</a></li>
    <li><a href="#third">Third</a></li>
    <li><a href="#fourth">Fourth</a></li>
    <li><a href="#fifth">Fifth</a></li>
  </ul>
</nav>

<section class="no-spy">
    Don't spy me!
</section>
<section class="block" id="first">
    First
</section>
etc...

Basically I only want the active state to show when a targeted element from the navbar is actually showing. Any ideas? Thanks in advance!


回答1:


The same happened to me, this is what I did.
I don't know if it's the best way to do it but it works.
Here's the code in your fiddle: http://jsfiddle.net/ZGsPm/1/

You add extra list items where your ignored sections go and add them a class ("ignore" in the example) and an id.

<body data-spy="scroll" data-target=".main-nav">
<nav class="main-nav">
  <ul class="nav">
    <li class="ignore"><a href="#no-spy-first"></a></li>
    <li><a href="#first">First</a></li>
    <li><a href="#second">Second</a></li>
    <li><a href="#third">Third</a></li>
    <li><a href="#fourth">Fourth</a></li>
    <li><a href="#fifth">Fifth</a></li>
    <li class="ignore"><a href="#no-spy-second"></a></li>
  </ul>
</nav>

Then you add the corresponding id to those sections so you can reference them from the list item.

<section class="no-spy" id="no-spy-first">
    Don't spy me!
</section>

<section class="block" id="first">
    First
</section>
...
<section class="no-spy last" id="no-spy-second">
    Don't spy me!
</section>

And finally, in Javascript (after you called the scrollspy function):

$('.ignore').css({'visibility':'hidden', 'width':'0%'});

Hope this helps!



来源:https://stackoverflow.com/questions/22915413/bootstrap-3-scrollspy-remove-active-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!