특정 요소가 브라우저에 보여질 때 감지하기
html(sample)
...
<div class="box"></div>
<div class="box"></div>
<div class="box_change bg1"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box_change bg2"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box_change bg3"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box_change bg4"></div>
<div class="box"></div>
<div class="box"></div>
...
scss(sample)
//
$bgColors: (rgba(0, 255, 255, 0.3), rgba(255, 255, 0, 0.3), rgba(255, 0, 105, 0.5), rgba(105, 50, 255, 0.5));
// IntersectionObserver 확인용
.box {
margin: 2rem;
height: 40rem;
background-color: rgba(255, 0, 0, 0.3);
}
.box_change {
margin: 2rem;
height: 70rem;
background-color: rgba(255, 0, 255, 0.3);
transition: background-color 0.5s ease 0.3s;
@for $i from 1 through length($bgColors) {
&.bg#{$i} {
background-color: nth($bgColors, $i);
}
}
&.show {
background-color: rgba(0, 0, 0, 0.7);
}
}
javascript
<script setup>
//
const io = (targets, ...callback) => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
// 브라우저에 보여질 때
if(entry.isIntersecting) {
callback[0](entry)
}
// 브라우저에서 사라졌을 때
else {
callback[1](entry)
}
})
})
// observer.observe(target)
targets.forEach(target => {
observer.observe(target)
})
}
const target = document.querySelectorAll(".box_change")
const showOn = (e) => {
console.log("show on", e.target.className, e.target)
e.target.classList.add("show")
}
const showNo = (e) => {
console.log("show no")
e.target.classList.remove("show")
}
io(target, showOn, showNo)
</script>
new IntersectionObserver 를 이용하여 특정 요소가 화면에 보여질 때를 감지할 수 있다
끝.