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

b0n*_*0nd 2 browser jquery scroll dimensions

我有一个菜单:

  <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>
Run Code Online (Sandbox Code Playgroud)

我希望这取决于浏览器的滚动条位置,"active"类是正确的<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');
} 
Run Code Online (Sandbox Code Playgroud)

我对jQuery Dimensions属性不太熟悉,所以这段代码没有多大意义,但我希望你能理解.

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

谢谢 :)

Bry*_*yan 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

即使上述内容不在正确的轨道上,还有一些其他注意事项可能有所帮助.像这样的线路$('#m1').parent().addClass('active').siblings().removeClass('active');很可能没有达到预期的效果.它不是将"活动"类添加到li中,然后将其从li的兄弟中删除,而是实际将类添加到父级ul并将其从ul的兄弟中删除.尝试.parent()从每一行删除,这应该工作.

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

希望这可以帮助.