IntersectionObserver
by hohoya33
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
<div class="slide slide--intro">
<h1>Intersection Observer Demo</h1>
</div>
<div class="slide">
<div class="box box--spin"><span>Spin</span></div>
</div>
<div class="slide">
<div class="box box--grow"><span>Grow</span></div>
</div>
<div class="slide">
<div class="box box--move-right"><span>Move Right</span></div>
</div>
CSS
body {
background: #eee;
}
.slide {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.slide--intro {
flex-direction: column;
}
.box {
display: flex;
align-items: center;
justify-content: center;
width: 150px;
height: 150px;
color: #fff;
text-align: center;
background-color: DeepPink;
transition: -webkit-transform 1s ease-in;
transition: transform 1s ease-in;
transition: transform 1s ease-in, -webkit-transform 1s ease-in;
}
.box--spin.box--visible {
-webkit-transform: rotate(1080deg);
transform: rotate(1080deg);
}
.box--grow.box--visible {
-webkit-transform: scale(1.5);
transform: scale(1.5);
}
.box--move-right.box--visible {
-webkit-transform: translateX(50px);
transform: translateX(50px);
}
JavaScript
const io = new IntersectionObserver(entries => {
entries.forEach(entry => {
// 관찰 대상이 viewport 안에 들어온 경우
if (entry.intersectionRatio > 0) {
entry.target.classList.add('box--visible');
}
// 그 외의 경우
else {
entry.target.classList.remove('box--visible');
}
})
})
const boxElList = document.querySelectorAll('.box');
boxElList.forEach((el) => {
io.observe(el);
})