Domanda

Sto usando jQuery per guidare le mie pagine scorrimento e cambiare il colore di un elemento nav per corrispondere alla sezione sei. Tutto sta lavorando bene, ma lo script sta ignorando l'ultima sezione della pagina (Contact).

Questo è in gran parte basata su un'altra domanda qui su Stack, ma ho modificato il codice per soddisfare le mie esigenze e poi corse in questione.

Terreno di prova: 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');
    }
});
È stato utile?

Soluzione

I think the following line is where the problem lies:

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

Specifically topsArray[i+1] is undefined for the last iteration of i. Try pushing one more value into topsArray that includes the height of the entire page.

topsArray = $sections.map(function(){
               return $(this).position().top - 100;
            }).get(),
topsArray.push(document.height);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top