htmlで
<a hreh=“#about”>ABOUT</a>
とすれば、id属性に「about」がついた箇所に移動できますが、一瞬で画面が変わってしまい味気なさがあります。
そこでjQueryを使ってヌルッと移動させる方法を紹介します。
htmlは以下です。
<a class=“goSection” href=“#first”>FIRST</a>
<a class=“goSection” href=“#second”>SECOND</a>
<section id="first">
FIRST
</section>
<section id="second">
SECOND
</section>
goSectionというクラスがついた要素がクリックされた時、その要素のhref属性の値がついた箇所に移動するという処理をします。
$(".goSection").on("click", function() {
// クリックされた要素のhref属性の値を取得 例:#first
const scrollTarget = $(this)[0].attributes[1].nodeValue;
// 取得した値のid属性がついた要素の位置を取得
const offsetTop = $(scrollTarget).offset().top;
// 取得した箇所に移動
$("html, body").animate({ scrollTop: offsetTop }, 200);
return false;
});
以上です。