1

我有一个数字数组。0,136,1084,3521,3961,5631,6510,7901,8204 (它们是一页上所有部分的当前 scrollTops。)我正在尝试找到一种方法来获取当前窗口 scrollTop 并找出哪个这些值当前介于两者之间,因此当页面滚动时,活动导航项会切换。

目前,在滚动时,“当前页面”会跳过 0 并直接进入数组中的 1,因此无法捕捉到最后一页。

currentPage = 0;
divOffset = new Array();

function setCurrentPage() {
    divOffset = []; //this ends up as 0,136,1084,3521,3961,5631,6510,7901,8204

    //get offset and ID of each section and add to array.
    $(".section").each(function() {
        sectionOffset = $(this).offset();
        divOffset.push(Math.round(sectionOffset.top));
    }); 

    bodyOffset = $(window).scrollTop(); 

    for(i=0; i < divOffset.length; i++) {
        if( divOffset[i] >= bodyOffset ) {
            currentPage = i;
            $('#mainNav li').removeClass("active");
            $("#mainNav li #a-" + currentPage).parent().addClass("active");
            return false;
        }
    }   

}

我的导航看起来像这样:

<ul id="mainNav">
    <li class="active"><a href="#a-0" class="navA" id="a-0">home</a></li>
    <li class="menuLI"><a>works</a>
        <ul>
            <li><a href='#a-1' class='navA' id='a-1'>Websites</a></li>
            <li><a href='#a-2' class='navA' id='a-2'>Illustrations</a></li>
            <li><a href='#a-3' class='navA' id='a-3'>Photomanipulations</a></li>
            <li><a href='#a-4' class='navA' id='a-4'>Glam Guitars</a></li>
            <li><a href='#a-5' class='navA' id='a-5'>Logos</a></li>
            <li><a href='#a-6' class='navA' id='a-6'>Photography</a></li>
        </ul>
    </li>
    <li><a href="#a-7" class="navA" id="a-7">about</a></li>
    <li><a href="#a-8" class="navA" id="a-8">contact</a></li>
</ul>

您可以在这里查看:http: //glowtagdesign.com/index2.php#a-0

4

1 回答 1

2

假设数组已排序,试试这个:

var i;
for (i = 0; i < arr.length && pos < arr[i]; i++)
{
}
// i is now the number of items in the array less than pos
// pos is less than the first item -> 0
// pos is greater than the last item -> arr.length
于 2012-06-07T23:59:58.463 回答