提问者:小点点

在视区中未显示时从元素中移除类


我正在做一个网站,有固定的辅助导航到右侧的视口。使用waypoint,当特定的id出现在视口底部时,我可以向导航锚点元素添加一个类。但是,我不知道如何做的是,当元素中的元素不再在视口中时,从该元素中移除该类。现在,我的导航将从活动类获得适当的样式,但当我向下滚动页面时,每个导航元素将保持活动类的样式。当元素不再显示在屏幕上时,我需要移除活动类。谢谢你的帮助。

jQuery:

$("#logo").waypoint(function(){
    $("#logo-nav").addClass('active');
});

$("#design").waypoint(function(){
    $("#design-nav").addClass('active');
});

$("#outdoor").waypoint(function(){
    $("#outdoor-nav").addClass('active');
});

$("#online").waypoint(function(){
    $("#online-nav").addClass('active');
});

$("#photo").waypoint(function(){
    $("#photo-nav").addClass('active');
});

$("#video").waypoint(function(){
    $("#video-nav").addClass('active');
});

实时html页面:

http://dai1.designangler.com/work


共2个答案

匿名用户

在每个AddClass()之前添加此行:

$('.active').removeClass('active');

如果您为waypoint元素提供了一个公共类,那么您可以将上面的所有代码替换为:

$(".waypoint-element").waypoint(function(){
    $('.active').removeClass('active');
    $('#' + this.id + '-nav').addClass('active');
});

匿名用户

当到达一个路径点时,您只需从所有导航链接中删除active类,然后将其添加到当前活动的路径点。

var setActive = function(id) {
    $(".nav > a").removeClass('active');
    $(id).addClass('active');
}

$("#logo").waypoint(function(){
    setActive("#logo-nav");
});
// ...