jQuery
ナビゲーションに「current(カレント)」を付与する
現在のページのURLと各ナビゲーションリンクのURLを比較し、一致した場合に「class="is-current"」を追加する
HTML
jQuery
$(function () {
// 現在のページパスを取得し、index.html を除去
let currentPath = window.location.pathname.replace(/index\.html$/, '');
if (!currentPath.endsWith('/')) currentPath += '/';
// すべてのナビゲーションリンクをチェック
$('.nav__item a').each(function () {
let linkPath = $(this).attr('href').replace(/index\.html$/, '');
if (!linkPath.endsWith('/')) linkPath += '/';
// サブディレクトリを含む startsWith 判定
if (currentPath.startsWith(linkPath)) {
//[.nav__item a] にクラスを付与する場合
$(this).addClass('is-current');
//linkの親 li.nav__item にクラスを付与する場合
$(this).closest('.nav__item').addClass('is-current');
}
});
});