画面をスクロールして、要素が画面内に入った時にアニメーションを発動させるIntersectionObserverの使い方を学んだ。
IntersectionObserverとは?
要素が画面に入ったか監視する機能のこと。
📱 画面の外にある → 見えない状態
↓ スクロール
📱 画面に入った!→ アニメーション発動
scrollイベントで位置を計算して表示するより、シンプルで高速に処理ができ、軽量とのこと。
コード例
Javascript
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
}
});
});
const targets = document.querySelectorAll('.fade-in');
targets.forEach((target) => {
observer.observe(target);
});
css
/* 普段は隠れている */
.fade-in {
opacity: 0;
transform: translateY(30px);
transition: opacity 0.6s ease, transform 0.6s ease;
}
/* visibleクラスがついたら表示 */
.fade-in.visible {
opacity: 1;
transform: translateY(0);
}
Javascript解説
// Observer作成
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// 画面に入った時の処理
entry.target.classList.add('visible');
}
});
});
Observerという監視員を作成するコード。
new IntersectionObserver()で監視員を作成、
entry.isIntersectingは画面にはいったらTrueになるので
if文の条件式に使用し、画面に入った時の処理を記述する。
上記コードは画面に入った際に要素のclassにvisibleを追加する。
画面に入った時以外のコードについては定型文なのでそのまま使用する。
//監視したい要素を登録する
const targets = document.querySelectorAll('.fade-in');
targets.forEach((target) => {
observer.observe(target);
});
監視したい要素を一つずつ取り出し、observerに登録する。
コメント