0

我正在使用 jQuery 来引导我的页面滚动并更改导航项的颜色以对应于您所在的部分。一切正常,但脚本忽略了页面上的最后一部分(联系方式)。

这主要基于 Stack 上的另一个问题,但我已经修改了代码以满足我的需要,然后遇到了这个问题。

测试站点: 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');
    }
});
4

1 回答 1

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);
于 2011-11-29T19:36:20.033 回答