0

我正在尝试构建一个“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及其与顶部的距离(以 px 为单位)组成:

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
}

需要明确的是,如果用户向下滚动页面 3000 像素,该函数应该返回c.

4

2 回答 2

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;
}
于 2012-10-18T13:12:25.310 回答
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一样工作

于 2012-10-18T12:24:30.790 回答