我希望導航鏈接具有「激活」類並在滾動時更改。我只有在用戶點擊鏈接時才能使用該代碼。如果用戶通過頁面手動滾動,則活動類不會更改。有什麼建議麼?更改導航滾動時激活
$(document).ready(function() {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function() {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 700, 'swing', function() {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('nav a').each(function() {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('nav ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
<!-- navigation -->
<nav>
<ul>
<li><a href="#bmi">text</a></li>
<li><a href="#health">text</a></li>
<li><a href="#home" class="active">text</a></li>
</ul>
</nav>
</header>
<section id="home">
</section>
<section id="health">
</section>
<section id="bmi">
</section>
你可以分享你的HTML? –
我添加了導航和部分html – Shaw