滚动到锚点时,将类添加到nav

时间:2016-04-19 15:53:06

标签: javascript jquery html

这是动态的。导航根据页面而变化。这里的代码在滚动到该部分时向导航添加一个类,然后在滚动过去时将其删除。问题是它只会在您向下滚动而不是通过该部分时删除。如何在向上滚动的同时删除类,同时实现添加类并在向下滚动时将其删除?

jQuery( document ).ready(function() {
    var sectionelements = jQuery('.nav li');
    (function(jQuery) {

    var scrolling = function(){
        jQuery(sectionelements).each(function(){
            var object=jQuery('#'+this);
            var wh = jQuery(window).height();
            var st = jQuery(document).scrollTop();
            var ot = jQuery(object).offset().top;
            var eh = jQuery(object).height();                   
            var href="a[href*=#"+object.attr('id')+"]";
            if(st>ot){
                jQuery(href).addClass('posreached');
            }
            if (st>ot+eh) {
                jQuery(href).removeClass('posreached');
            };
        })
    };
        jQuery(window).scroll(scrolling);
        jQuery(window).bind('resize orientationchange',scrolling);

//fire initial scroll
jQuery(window).scroll();
    })(jQuery);
});

2 个答案:

答案 0 :(得分:0)

这样:

if(st>ot){
    jQuery(href).addClass('posreached');
}
if (st>ot+eh) {
    jQuery(href).removeClass('posreached');
};

即使在第二个状态中第一个也是如此,所以你需要添加:

if(st>ot || st<ot+eh){
    jQuery(href).addClass('posreached');
}

试一试

答案 1 :(得分:0)

我将这些用于我的条件并且有效

{{1}}