将offset()。top与对象属性进行比较

时间:2012-10-18 12:15:23

标签: javascript jquery

我正在努力建立一个' scrollSpy'类型功能。我不知道如何将参数与对象中的某些值进行比较,并返回(数字上)最高值的名称。

我有一些标记:

<ul class="nav">
    <li><a href="a"></a></li>
    <li><a href="b"></a></li>
    <li><a href="c"></a></li>
    <li><a href="d"></a></li>
    <li><a href="e"></a></li>
    <li><a href="f"></a></li>
</ul>

<section id="a" class="scrollspy"></section>
<section id="b" class="scrollspy"></section>
<section id="c" class="scrollspy"></section>
<section id="d" class="scrollspy"></section>
<section id="e" class="scrollspy"></section>
<section id="f" class="scrollspy"></section>

一些脚本创建了一个由section组成的对象及其距离顶部的距离:

var obj = {
    sectionOffset: {},
    scrollSpy: function (scrolled) {
        // This should look in the object with the offset values, and from all
        // the values that (scrolled) is higher than, take the largest, and
        // return its name.
    }
}


$(function () {

    $(window).scroll(function () {
        obj.scrollSpy($(document).scrollTop()); 
    });

    // Create an object consisting of all elements I want to 'spy' on.
    // Names and values are made of element ID and top offset respectively.
    $('.scrollspy').each(function () {
        obj.sectionOffset[$(this).attr('id')] = (parseInt($(this).offset().top));
    });

});

在循环遍历我想要的元素之后,它会产生一个像:

这样的对象
{
    d: 5195,
    b: 3245,
    a: 1319,
    f: 5682,
    c: 2139,
    e: 3343
}

为了清楚起见,如果用户向下滚动3000px,该函数应返回c

2 个答案:

答案 0 :(得分:1)

scrollSpy: function (scrolled) {

    var highest = 0, highestName = null;

    // iterate through the offsets
    $.each(obj.sectionOffset, function(name, val) {
        // check that scrolled is higher than the value, and that it's the highest found so far
        if (scrolled > val && val > highest) {
            highest = val;
            highestName = name;
        }
    });

    return highestName;
}

答案 1 :(得分:0)

$('.scrollspy').each(function () 
{
    if(($(this).offset().top + $(this).height()) > 0)
    {
       //this is the one you are looking for.

       return false; //break the loop.
    }
});

这将像scrollSpy fiddle

一样工作