스크롤 시 요소 애니메이션
Coddy HTML 여정의 JavaScript in Action 섹션에 포함된 레슨 — 27개 중 19번째.
때때로 우리는 요소들이 스크롤하는 동안 뷰포트에 들어올 때 애니메이션(페이드 인, 슬라이드 인, 줌 등) 효과를 주기를 원합니다.
이는 종종 요소가 화면에 보이는지 확인한 다음, CSS 애니메이션이나 트랜지션을 트리거하는 클래스를 추가함으로써 수행됩니다.
먼저, 간단한 HTML 요소를 만들어 보겠습니다:
<div class="animate-on-scroll">This element will animate when scrolled into view</div>다음으로 애니메이션을 위한 CSS를 추가합니다:
.animate-on-scroll {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.5s ease, transform 0.5s ease;
}
.animate-on-scroll.visible {
opacity: 1;
transform: translateY(0);
}이제 요소가 뷰포트 안에 들어오는 것을 감지하는 JavaScript 함수를 만들어 보겠습니다. 여러 요소가 있을 수 있으므로, forEach를 사용하여 각 요소를 반복하며 뷰포트에 대한 각 요소의 위치를 확인합니다.
function checkScroll() {
const elements = document.querySelectorAll('.animate-on-scroll');
elements.forEach(element => {
// 뷰포트에 대한 요소의 위치 가져오기
const position = element.getBoundingClientRect();
// 요소가 뷰포트 안에 있는 경우
if(position.top < window.innerHeight) {
element.classList.add('visible');
}
});
}
// 스크롤 시 실행
window.addEventListener('scroll', checkScroll);
// 페이지 로드 시 한 번 실행
checkScroll();animate-on-scroll 클래스를 가진 요소가 뷰포트에 들어오면, 스크립트가 visible 클래스를 추가하여 애니메이션을 트리거합니다.
챌린지
쉬움루프 내부에서 if 문을 생성하세요.
- 조건은 다음과 같아야 합니다: 요소의 top position이
window.innerHeight - 50보다 작은지 확인합니다. - 조건이 참이면,
.classList.add("active")를 사용하여 해당 요소에active클래스를 추가합니다.
이렇게 하면 요소가 뷰포트 안으로 스크롤될 때마다(화면 하단에서 50px 이내), 부드럽게 페이드 인됩니다.
직접 해보기
<!DOCTYPE html>
<html>
<head>
<title>Scroll Animation Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Discover the Beauty of Nature</h1>
<p>Scroll down to reveal the magic</p>
</header>
<div class="container">
<div class="fade-in card">
<h2>Mountains</h2>
<p>Standing tall and timeless, mountains remind us of strength and stability.</p>
</div>
<div class="fade-in card">
<h2>Forests</h2>
<p>Forests are the lungs of our planet, offering peace and endless green beauty.</p>
</div>
<div class="fade-in card">
<h2>Rivers</h2>
<p>Calm or powerful, rivers flow endlessly, connecting life along their paths.</p>
</div>
<div class="fade-in card">
<h2>Deserts</h2>
<p>Silent and vast, deserts teach us resilience and the value of every drop of water.</p>
</div>
<div class="fade-in card">
<h2>Oceans</h2>
<p>The oceans cover most of our Earth, a mysterious world full of wonder and life.</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.