jQuery:根据浏览器滚动条位置将css类添加到菜单项

我有一个菜单:

 

我希望这取决于浏览器的滚动条位置, “active”类是正确的

  • 元素。

    这就是我的看法:

      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 Dimensions属性不太熟悉,所以这段代码没有多大意义,但我希望你能理解。

    如果有人能告诉我如何使这项工作,那将是非常酷的。

    谢谢 :)

    目前还不完全清楚你正在尝试做什么,但我会抓住它。 要获得窗口垂直滚动的数量,您将需要使用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'); 可能没有做你期望的事情。 它不是将“active”类添加到li中,然后将其从li的兄弟中删除,而是实际将类添加到父级ul并将其从ul的兄弟中删除。 尝试从每一行中删除.parent() ,这应该有效。

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

    希望这可以帮助。