基于滚动忽略最后一节的jQuery类更改 [英] jQuery class change based on scroll ignoring last section
问题描述
我正在使用jQuery引导页面滚动并更改导航项的颜色以与您所在的部分相对应.一切正常,但是脚本忽略了页面的最后部分(联系).
I'm using jQuery to guide my pages scrolling and change the color of a nav item to correspond to the section you're in. Everything's working well, but the script is ignoring the last section on the page (Contact).
这很大程度上是基于Stack上的另一个问题,但是我已经修改了代码以适合自己的需求,然后遇到了这个问题.
This is largely based on another question here on Stack, but I've modified the code to fit my needs and then ran into the issue.
测试地点: 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:
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');
}
});
推荐答案
我认为问题出在以下几行:
I think the following line is where the problem lies:
if(top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1]){
特别是对于i
的最后一次迭代,未定义topsArray[i+1]
.尝试将包括整个页面高度的另一个值推入topsArray中.
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);
这篇关于基于滚动忽略最后一节的jQuery类更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!