アンカーリンクのスクロール処理をスムーススクロールにする為の処理をまとめました。
jQueryは使用せず、javascriptのみで実装します。
注意点
はじめに、今回実装する方法の注意点を以下にまとめました。
- スクロール速度を調節できない
- イージングを設定できない
- ページ外アンカーリンクには対応していない
スクロール速度とイージング調節対応版は、javascriptのみ使用Ver、GSAP使用Verをそれぞれ別記事にてまとめる予定です。ページ外アンカーリンク対応は今のところ予定していません。
コード
document.querySelectorAll("a[href^='#']").forEach(link => {
link.addEventListener("click", function (e) {
e.preventDefault();
const targetId = this.getAttribute("href");
const target = document.querySelector(targetId);
const targetPosition = target.getBoundingClientRect().top + window.scrollY;
const headerHeight = document.querySelector(".header").offsetHeight;
window.scroll({
behavior: "smooth",
top: targetPosition - headerHeight,
})
});
});
1行目 対象のリンクを取得
document.querySelectorAll("a[href^='#']")
属性セレクタを使用して、#からはじまるリンクを持つa要素を取得します。
3行目 デフォルトの機能を止める
e.preventDefault();
アンカー先へ移動する処理を止めます。
6行目 アンカー先の要素の位置を取得
const targetPosition = target.getBoundingClientRect().top + window.scrollY;
要素.getBoundingClientRect().top + window.scrollY
で対象の位置(y座標)を取得します。
7行目 ヘッダーの高さ取得
const headerHeight = document.querySelector(".header").offsetHeight;
ヘッダーが上部追従等の場合、その高さ分ずらすことで調整しますので、ここで高さを取得します。
9~行目 window.scrollの設定
window.scroll({
behavior: "smooth",
top: targetPosition - headerHeight,
})
behavior: "smooth"
にすることでスムーススクロールになります。
window.scroll特定の位置へスクロールさせる
デモ
See the Pen アンカーリンクのスムーススクロール処理 by yoshi (@mikanbako) on CodePen.
まとめ
- window.scrollのbehaviorプロパティを'smooth'に設定することでスムーススクロール可能
- スクロール速度やイージングを調整したい場合は別の方法で実装