【发布时间】:2012-02-25 01:41:08
【问题描述】:
目前我有点卡在一个问题上,似乎无法找到解决办法。
我正在尝试在一个站点上构建一个固定导航,当您滚动以及单击时,活动类会在该站点上发生变化。这是我试图实现的导航的一个很好的例子 - kiskolabs.com/
我几乎已经可以使用以下代码了,但是在前 2 个导航项正常工作后,我发现导航项状态在正确的位置没有改变。不知道我做错了什么,但锚链接仍然去正确的地方,只是活动状态在一对夫妇之后没有改变。有什么想法吗?下面是代码。
HTML
<section id="1">
<nav>
<ul>
<li><a href="#1">1</a></li>
<li><a href="#2">2</a></li>
<li><a href="#3">3</a></li>
<li><a href="#4">4</a></li>
</ul>
</nav>
<p>All content here</p>
</section>
<section id="2">
<p>All content here</p>
</section>
<section id="3">
<p>All content here</p>
</section>
<section id="4">
<p>All content here</p>
</section>
我正在使用 jquery:
$(document).ready(function () {
var $sections = $('section'); // all content sections
var $navs = $('nav > ul > li'); // all nav sections
var topsArray = $sections.map(function() {
return $(this).position().top - 300; // make array of the tops of content
}).get(); // sections, with some padding to
// change the class a little sooner
var len = topsArray.length; // quantity of total sections
var currentIndex = 0; // current section selected
var getCurrent = function( top ) { // take the current top position, and see which
for( var i = 0; i < len; i++ ) { // index should be displayed
if( top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1] ) {
return i;
}
}
};
// on scroll, call the getCurrent() function above, and see if we are in the
// current displayed section. If not, add the "selected" class to the
// current nav, and remove it from the previous "selected" nav
$(document).scroll(function(e) {
var scrollTop = $(this).scrollTop();
var checkIndex = getCurrent( scrollTop );
if( checkIndex !== currentIndex ) {
currentIndex = checkIndex;
$navs.eq( currentIndex ).addClass("selected").siblings(".selected").removeClass("selected");
}
});
});
【问题讨论】:
标签: jquery dynamic navigation scroll fixed