スクロール検知 IntersectionObserver
code::JavaScript
const child = document.querySelector('.child');
const cb = function(entries, observer) {
// entryには、observe(child)のchildが入ってくる
entries.forEach(entry => {
if(entry.isIntersecting) { // 入って行く時
entry.target.classList.add('inview');
// observer.unobserve(entry.target); // 一回入った時点で監視を終わらす
} else { // 出て行く時
entry.target.classList.remove('inview');
}
});
}
const options = {
root: null,
rootMargin: "-300px 0px",
threshold: 0, 0.5, 1
};
// 基本構文 第一引数としてコールバック関数・第二引数としてオプションを渡せる
const io = new IntersectionObserver(cb, options);
io.observe(child);
JavaScript