jQuery : add css class to menu item based on browser scroller position

后端 未结 1 1516
别跟我提以往
别跟我提以往 2020-12-15 02:04

I have a menu:

  
相关标签:
1条回答
  • 2020-12-15 02:52

    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.

    0 讨论(0)
提交回复
热议问题