jQuery : add css class to menu item based on brows

2019-01-23 00:48发布

问题:

I have a menu:

  <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>

I want that depending of browser's scroller position, the "active" class goes the correct < li > element.

This is how I see it :

     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');
} 

I am not very familiar with jQuery Dimensions properties so this code doesn't make much sense, but I hope you get the idea.

If someone could tell me how to make this work, it would be really cool.

Thanks :)

回答1:

It's not entirely clear what it is you're trying to do, but I'll take a stab at it. To get the amount the window has scrolled vertically you'll want to use jQuery's scrollTop() function. The height() function gives you the height in pixels of the element upon which it is called, so it won't be very useful if the scroll value is what you want. Something like this might be closer to what you need:

// 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");
    }
}

Even if the above isn't on the right track, there are a couple other things to note that might help. The lines such as $('#m1').parent().addClass('active').siblings().removeClass('active'); are likely not doing what you expect. Rather than adding the 'active' class to the li and then removing it from the li's siblings, it's actually adding the class to the parent ul and removing it from the ul's siblings. Try removing .parent() from each line and that should work.

Also, since you are using == in your if conditions, the class will be added only when the value is exactly 500 or 1000 etc. which I doubt is what you intend. That's why in the code above I changed it to be <= for the conditional statements.

Hope this helps.