【问题标题】:jquery else and if statements help on scroller positionjquery else 和 if 语句有助于滚动位置
【发布时间】:2011-12-21 19:30:21
【问题描述】:

我想根据滚动位置添加一个活动类,感谢我发现这个已经发布了:

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

我对本教程有一个额外的导航项,但不知道如何安排 if、else if 和 else 语句。

$(window).scroll(function() {    
// find the li with class 'active' and remove it
$("#navigation 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) {
    $("#nav-welcome").addClass("active");
}
else if (scroll <= 1000) {
    $("#nav-about").addClass("active-purple");
}
else if (scroll <= 1500) {
    $("#nav-portfolio").addClass("active");
}
else {
    $("#nav-contact").addClass("active-purple");
}
});

我得到了两个活动课程,其中我使用了两个 else if。

非常感谢。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    试试这个:

    if (scroll >= 1500)  {
        $("#nav-portfolio").addClass("active");
    } else if (scroll >= 1000) {
        $("#nav-about").addClass("active-purple");
    } else if (scroll >= 500) {
        $("#nav-welcome").addClass("active");
    } else {
        $("#nav-contact").addClass("active-purple");
    }
    

    【讨论】:

    • 感谢您的回复。虽然它正在激活最后一个 else 语句,但它部分工作 - nav-contact 在 nav-welcome 和 nav-about 之间滚动,当向上滚动时,它会激活 nav-contact 而不是 od nav-welcome。
    • 你设置它的方式有点令人困惑。当您位于页面顶部时,您希望它在什么位置?
    猜你喜欢
    • 2016-07-15
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多