2

我有一个菜单:

  <ul class="menu-bottom">
  <li id="m1" class="active"><a id="1" href="#"><span>Link 1</span></a></li>
   <li id="m2"><a id="2" href="#"><span>Link 2</span></a></li>
   <li id="m3"><a id="3" href="#"><span>Link 3</span></a></li>
</ul>

我希望根据浏览器的滚动条位置,“活动”类进入正确的<li>元素。

这就是我的看法:

     if ($(document).height() == 500) {
$('#m1').parent().addClass('active').
siblings().removeClass('active');
}

     if ($(document).height() == 1000) {
$('#m2').parent().addClass('active').
siblings().removeClass('active');
}

     if ($(document).height() == 1500) {
$('#m2').parent().addClass('active').
siblings().removeClass('active');
} 

我对 jQuery 维度属性不是很熟悉,所以这段代码没有多大意义,但我希望你能明白。

如果有人能告诉我如何完成这项工作,那就太酷了。

谢谢 :)

4

1 回答 1

11

目前尚不完全清楚您要做什么,但我会尝试一下。要获得窗口垂直滚动的量,您需要使用 jQuery 的scrollTop()函数。该height()函数为您提供调用它的元素的高度(以像素为单位),因此如果滚动值是您想要的,它不会很有用。像这样的东西可能更接近你需要的东西:

// bind a function to the window's scroll event, this will update
// the 'active' class every time the user scrolls the window
$(window).scroll(function() {    
    // find the li with class 'active' and remove it
    $("ul.menu-bottom li.active").removeClass("active");
    // get the amount the window has scrolled
    var scroll = $(window).scrollTop();
    // add the 'active' class to the correct li based on the scroll amount
    if (scroll <= 500) {
        $("#m1").addClass("active");
    }
    else if (scroll <= 1000) {
        $("#m2").addClass("active");
    }
    else {
        $("#m3").addClass("active");
    }
}

即使上述内容不在正确的轨道上,还有其他一些需要注意的事项可能会有所帮助。诸如此类的行$('#m1').parent().addClass('active').siblings().removeClass('active');可能不会按照您的预期进行。与其将“活动”类添加到 li,然后将其从 li 的兄弟姐妹中删除,它实际上是将类添加到父 ul 并将其从 ul 的兄弟姐妹中删除。尝试.parent()从每一行中删除,这应该可以。

此外,由于您在 if 条件中使用 == ,因此仅当值恰好为 500 或 1000 等时才会添加该类。我怀疑这是您想要的。这就是为什么在上面的代码中我将其更改为 <= 用于条件语句。

希望这可以帮助。

于 2010-04-24T04:59:30.863 回答