-->

基于jQuery的滚动变化类忽略最后一节(jQuery class change based on

2019-10-28 09:37发布

我使用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');
    }
});

Answer 1:

我认为以下行是问题所在:

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);


文章来源: jQuery class change based on scroll ignoring last section