2011-11-29 46 views
0

我使用jQuery来指导我的页面滚动和更改导航项目的颜色对应于你,一切的工作是很好的部分,但脚本被忽略页面上的最后一部分(联系人)。jQuery的类变化忽略最后一节

这主要是基于这里堆栈另一个问题,但我已经修改了代码,以适合我的需要,然后跑进了问题。

测试地点: http://dev4.dhut.ch/

HTML:

<nav> 
    <ul> 
     <li class="active"><a href="#music" title="Music">MUSIC</a></li> 
     <li><a href="#photos" title="Photos">PHOTOS</a></li> 
     <li><a href="#lyrics" title="Lyrics">LYRICS</a></li> 
     <li><a href="#news" title="News">NEWS</a></li> 
     <li><a href="#info" title="Info">INFO</a></li> 
     <li><a href='#contact' title="Contact">CONTACT</a></li> 
    </ul> 
    <span></span> 
</nav> 

的JavaScript:

var $sections = $('section'), 
    $navs  = $('nav > ul > li'), 
    topsArray = $sections.map(function(){ 
         return $(this).position().top - 100; 
        }).get(), 
    len   = topsArray.length, 
    currentIndex = 0, 
    getCurrent = function(top){ 
         for(var i = 0; i < len; i++){ 
          if(top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1]){ 
           return i; 
          } 
         } 
        }; 

$(document).scroll(function(e){ 
    var scrollTop = $(this).scrollTop(), 
     checkIndex = getCurrent(scrollTop); 

    if(checkIndex !== currentIndex){ 
     currentIndex = checkIndex; 
     $navs.eq(currentIndex).addClass('active').siblings('.active').removeClass('active'); 
    } 
}); 
+0

这有点令人害怕,这完全是我的问题和完全相同的元素和类名。 o.o – Purag

+0

听起来像我们从同一个地方得到它:)检查twitter引导 - 他们有一个名为ScrollSpy的杀手插件,这样做更好。 Github上还有一个项目将它与页面内滚动相结合。 – technopeasant

回答

0

我认为下面一行是问题所在:

if(top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1]){ 

具体topsArray[i+1]没有定义的i最后一次迭代。尝试将更多值添加到包含整个页面高度的topsArray中。

topsArray = $sections.map(function(){ 
       return $(this).position().top - 100; 
      }).get(), 
topsArray.push(document.height); 
+0

像黄油一样。谢谢! – technopeasant