ナビゲーションリンクに「アクティブ」クラスがあり、スクロールするときに変更するようにします。ユーザーがリンクをクリックしたときのコードです。ユーザーがページを手動でスクロールしている場合、アクティブなクラスは変更されません。助言がありますか?ナビゲーションの変更スクロール時に有効
$(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を共有することができます。..実施例でありますか? –
navとsectionを追加しました。 – Shaw