我正在尝试构建一个“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
.