스크롤 시 요소 애니메이션
Coddy HTML 여정의 JavaScript 실전 섹션에 포함된 레슨. 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 문을 만드세요.
- 조건은 요소의 상단 위치가
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>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
JavaScript 실전의 모든 레슨
직접 연습해 보세요: Web 플레이그라운드