数组,检查当前值之间的2个数字

时间:2012-06-07 23:54:36

标签: javascript jquery

我有一系列数字。 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

1 个答案:

答案 0 :(得分:3)

假设数组已排序,请尝试:

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