概要
スクロールに合わせて、タイトルや画像をふわっと表示させたい時は、スクロールイベントを設定して実装していましたが、Intersection Observerを使用することでシンプルに実装できます。
施策
HTML
<div class="box"></div>
ページ内にboxというクラス名の要素を作ります。
CSS
.box {
width: 30%;
aspect-ratio: 1/1;
background-color: #000000;
}
.box.red{
background-color: #ff0000;
}
今回は黒いボックスが範囲内に入ると赤く変わるようにします。
JavaScript
document.addEventListener("DOMContentLoaded", () => {
const options = {
root: null,
rootMargin: "-200px -100px",
threshold: 0,
};
const targets = Array.from(document.querySelectorAll(".box"));
const callback = function (entries, observer) {
entries.map((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('red');
} else {
entry.target.classList.remove('red');
}
});
};
const observer = new IntersectionObserver(callback, options);
targets.map( target => {
observer.observe( target ); //監視を開始
});
});
document.addEventListener("DOMContentLoaded", () => {});
DOMContentLoadedでページのすべての要素が読み終わった後に中の処理を実行します。
const options = {
root: null,
rootMargin: "-200px -100px",
threshold: 0,
};
Intersection Observerのオプションを設定しています。
root
監視対象が交差確認するための要素。(交差領域)nullを指定している場合はブラウザサイズになります。
rootMargin
rootからどれくらいマージンを取るかの指定をします。記述方法はCSSのマージンと同じですが、「0」は「0px」とpxをつける必要があります。値がマイナスなのはブラウザサイズから内向きにマージンをとっているためです。
threshold
交差領域と監視対象のしきい値。0の時は交差領域と監視対象が重なり始めから、1の時は交差領域に監視対象が入ればイベントが発生します。
const targets = Array.from(document.querySelectorAll(".box"));
今回は複数のボックスに設定していますので、取得したボックスを配列にしています。
const callback = function (entries, observer) {
entries.map((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add('red');
} else {
entry.target.classList.remove('red');
}
});
};
コールバック関数です。交差した要素に対しては、クラス名「red」を追加して、それ以外は「red」を外すようにしています。
const observer = new IntersectionObserver(callback, options);
targets.map( target => {
observer.observe( target ); //監視を開始
});
IntersectionObserverを生成後、各ボックスに対して監視を開始しています。
最後に
ブラウザもある程度対応しているようですので、使用しても問題ないと思います。
コメントを投稿する