現在、スクロール位置が一致するセクション内にあるかどうかに基づいて特定のナビゲーションリンクを強調表示するjQueryプラグインを構築しています。メニューのハイライト表示(最適化)を使用したjQueryのページ内ナビゲーション
私はそれが現在動作している方法は、私が望むすべてをやっている。フィドルを参照してくださいDemo Fiddle
私は対応するセクション内にあるとき、リンクが適切に強調表示されます。また、私がセクションの外にいるときにハイライトを消したい。
は、私はそれここにやっている:私は2番目のセクションの内側とスクロールダウンしていたときに
if (scrollPos + settings.offset >= currentSectionTop && scrollPos + settings.offset < currentSectionBottom) {
// Get the section ID and corresponding nav link.
var currentSectionID = $currentSection.attr('id'),
$correspondingNavLink = sectionMap[currentSectionID];
// If the link isn't active already, make it so.
if (!$correspondingNavLink.hasClass('active')) {
$navLinks.removeClass('active');
$correspondingNavLink.addClass('active');
console.log('added active class');
}
// Because this is the correct section, exit.
return false;
} else {
if ($navLinks.hasClass('active')) {
$navLinks.removeClass('active');
console.log('removed active class');
}
}
問題が来ます。その場合、アクティブなクラスは継続的に追加および削除され(コンソールログを確認します)、これはまさに私が防止しようとしているものです。
これは、最初のセクション内でスクロールしているときには起こりません。なぜなら、これが各ループ内で最初にチェックされるためです。一致するため、ループを終了します。
結果がまさに私が望むものであっても、私は引き続き削除 - 削除 - 追加...サイクルを削除してこの小さな最適化を行いたいと思います。
どうすればいいですか?
非常に高く評価されました!
UPDATE:
JeyPackの答えをフォローアップした後、私は私が必要なものです。セクション外でスクロールするときにアクティブなクラスを削除するには、セクションが見つかったときにのみtrueに変更される変数を使用しました。 whileループの後で、もしその変数がまだfalseなら、それは私たちがどのセクションの外にもスクロールしたことを意味します。
ありがとうございました。私に正しい方向性と最適化を指示していただきありがとうございます。
ここで更新されたコードです:
function highlightNav() {
// Get the current scroll position.
var currentSectionID, $correspondingNavLink, $currentSection, currentSectionTop, currentSectionBottom,
scrollPos = $w.scrollTop() + settings.offset,
i = $sections.length,
found = false;
// Loop through each section.
while (--i >= 0) {
// get current section
$currentSection = $sections.eq(i);
currentSectionTop = $currentSection.offset().top;
currentSectionBottom = $currentSection.offset().top + $currentSection.outerHeight(true);
// If we scrolled inside the section...
if (scrollPos >= currentSectionTop && scrollPos < currentSectionBottom) {
// Get the section ID and corresponding nav link.
currentSectionID = $currentSection.attr('id');
$correspondingNavLink = sectionMap[currentSectionID];
found = true;
// Because this is the correct section, break.
break;
}
}
if (!found && $navLinks.hasClass('active')) {
$navLinks.removeClass('active');
}
// If the link isn't active already, make it so.
if ($correspondingNavLink && !$correspondingNavLink.hasClass('active')) {
$navLinks.removeClass('active');
$correspondingNavLink.addClass('active');
window.console.log('added active class', $correspondingNavLink);
}
}
これは確かに、よりエレガントであるが、今、追跡すべきではない部分の内側にスクロールしたときにハイライトが削除されません...あなたがいずれかを持っていますがその周りの方法? –
@Adi私は自分の答えを更新しました:新しい状態変数で、要求通りに動作するはずです。 – JeyPack