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

早过忘川 提交于 2019-11-28 22:10:59

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!