当页面滚动时,如何相对于部分更改nav li上的活动类?

时间:2017-12-01 21:00:17

标签: jquery html css css3 flexbox

当页面在我的固定顶部导航栏上滚动时,我需要更改活动的链接类。我怎么用jquery做到这一点?部分没有固定的高度。

HTML:

 <nav class="navbar navbar-toggleable-sm navbar-inverse main-navigation fixed-top">
            <div class="d-flex align-items-center content-nav-wrapper col-10 offset-1">
                <h1 class="mr-auto"><a href="index.html"><img src="images/site_logo.png" alt="logo"></a></h1>
                <button class="navbar-toggler navbar-toggler-right offcanvas-toggle menu-button" type="button"
                        data-toggle="offcanvas"
                        data-target="#js-bootstrap-offcanvas" aria-controls="navbarCollapse" aria-expanded="false"
                        aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-offcanvas navbar-offcanvas-touch navbar-offcanvas-right menu"
                     id="js-bootstrap-offcanvas">
                    <ul class="navbar-nav ml-md-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="#about">About</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#portfolio">Portfolio</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#team">Team</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#contact">Contact</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

<section class="d-flex about" id="about">
<!--Content-->
</section>

<section class="d-flex portfolio" id="portfolio">
<!--Content-->
</section>

<section class="d-flex team" id="team">
<!--Content-->
</section>

<section class="d-flex contact" id="contact">
<!--Content-->
</section>

我已经顺利滚动到了点击部分。也许它只需要修改?

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 800);
});

1 个答案:

答案 0 :(得分:0)

在这里,我的解决方案非常有效。

jQuery(window).scroll(function(){
    var $sections = $('section');
    $sections.each(function(i,el){
        var top  = $(el).offset().top-100;
        var bottom = top +$(el).height();
        var scroll = $(window).scrollTop();
        var id = $(el).attr('id');
        if( scroll > top && scroll < bottom){
            $('a.active-section-link').removeClass('active-section-link');
            $('a[href="#'+id+'"]').addClass('active-section-link');

        }
    })
});

$("nav").on("click","a", function (event) {

    event.preventDefault();
    var id  = $(this).attr('href'),
        top = $(id).offset().top;
    $('body,html').animate({scrollTop: top}, 800);
});