JSFiddle - React, Tailwind, and code Playground
by ken3desu
HTML
<div id="msg-box"><span id="msg"></span></div>
<div id="tgt"></div>
CSS
#tgt {
position: absolute;
height: 100px;
width: 100px;
top: 400px;
background: red;
}
#msg-box {
position: fixed;
top: 0;
}
html, body {
height: 300px;
width: 200px;
}
JavaScript
if(window.IntersectionObserver){// IntersectionObserver が未実装のブラウザ用のガード
let i = 0;
const observer = new IntersectionObserver((entries) => {
// entriesは監視対象すべてが入っているリストです
// @see https://developer.mozilla.org/ja/docs/Web/API/IntersectionObserverEntry
for(const e of entries) {
// isIntersecting プロパティに内、外の情報が入っています
i++;
if(e.isIntersecting){
document.getElementById('msg').innerText = i + '回発火 現在:IN';
}else{
document.getElementById('msg').innerText = i + '回発火 現在:OUT';
}
}
});
// オブザーバインスタンスのobserve メソッドに監視対象要素を引数として渡すことで監視がされるようになります
observer.observe(
document.getElementById('tgt')
)
}