我有一个导航栏和几个部分,我想在滚动这些部分时更改导航项的事件状态。
我有以下代码:
var sections = $('section')
, nav = $('nav')
, nav_height = nav.outerHeight();
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
sections.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
});
});
<header>
<section id="home">
<nav>
<div class="nav-container">
<ul>
<li><a href="#home" class="active">Home</a></li>
<li><a href="#service">Service</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</nav>
</section>
</header>
<section id="service"></section>
<section id="contact"></section>
当我向下滚动时它工作正常。当我向上滚动时几乎没问题,因为当我回到主页部分时它不会再次进入事件状态。
最佳答案
您的导航位于主页部分。
所以当你点击这里时:
var top = $(this).offset().top - nav_height,
您与顶部的偏移量是 0
当你检查时 if (cur_pos >= top && cur_pos <= bottom)
你的cur_pos
是-{navBarHeight}
尝试将您的导航移动到主页部分的外部和上方,或者将其考虑在内。
关于javascript - 更改滚动上导航项的事件状态及其一个小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59144175/