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

时间:2014-10-17 20:12:58

标签: javascript jquery html

我有一个网站,它在<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>

小提琴: http://jsfiddle.net/qfaeqo2w/

提前致谢,问候。

1 个答案:

答案 0 :(得分:1)

这是你追求的吗?

http://jsfiddle.net/0ytvjtme/

首先,我更改了计算scrollPoint以考虑标题的大小:

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

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

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

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

相关问题