导航锚点不'滚动jQuery时不能正确应用活动类

Nav anchor doesn't apply active class correctly while scroll jQuery

本文关键字:不能 应用 活动 jQuery 滚动 导航      更新时间:2023-09-26

我有一个网站,它在<header>元素的底部有一个粘性导航,只要我滚动到一个部分,它就会使用data-attributes激活一个类,这里的错误是:当我滚动active类时,它会添加到该部分的一半,即使滚动不根据该部分滚动。

我想要的是打开active类,只要我得到了每个部分的锚,我在下面留下我的代码,后面跟着一个jsfiddle,你可以看到问题出在哪里,我希望你们能帮助我。

HTML:

<header class="testheader">
    <nav id="cloud_nav" class="absolute">
            <ul>
                <li><a href="#" data-scroll="overview">Section 1</a></li>
                <li><a href="#" data-scroll="readiness">Section 2</a></li>
                <li><a href="#" data-scroll="collaboration">Section 3</a></li>
            </ul>
    </nav>
</header>    
<section data-anchor="overview" style="background: red; font-size: 25px;">
</section> 
<section data-anchor="readiness" style="background: green; font-size: 25px;">
</section>
<section data-anchor="collaboration" style="background: #ccc; font-size: 25px;">
</section>
</div> 

Javascript:

 <script type="text/javascript">
    // Sticky Nav
$('#cloud_nav a').on('click', function() {
    var scrollAnchor = $(this).attr('data-scroll'),
        scrollPoint = $('section[data-anchor="' + scrollAnchor + '"]').offset().top;
    $('body,html').animate({
        scrollTop: scrollPoint
    }, 500);
    return false;
})
var navOffset = $('#cloud_nav').offset().top;
$(window).scroll(function(){
    var scrollPos = $(window).scrollTop();

    if (scrollPos >= navOffset){
        $('#cloud_nav').removeClass('absolute');
        $('#cloud_nav').addClass('fixed_cloud_nav');
       $('section').each(function(i) {
            if ($(this).position().top <= scrollPos - 50) {
                $('#cloud_nav a.active').removeClass('active');
                $('#cloud_nav a').eq(i).addClass('active');
            }
        });
    } else {
        $('#cloud_nav').removeClass('fixed_cloud_nav');
        $('#cloud_nav').addClass('absolute');
        $('#cloud_nav a.active').removeClass('active');
        $('#cloud_nav a:first').addClass('active');
    }
});
</script>

Fiddle:http://jsfiddle.net/qfaeqo2w/

提前谢谢,问候。

这就是你想要的吗?

http://jsfiddle.net/0ytvjtme/

首先,我改变了计算scrollPoint的方式,以考虑标头的大小:

scrollPoint = $('section[data-anchor="' + scrollAnchor + '"]').offset().top - $('#cloud_nav').outerHeight();

然后,我们不是减去50个像素,而是添加检测滚动位置的导航高度:

if ($(this).position().top <= scrollPos + $('#cloud_nav').outerHeight())

锚点现在滚动到正确的位置,活动类看起来可以正确切换。