スクロール時の要素アニメーション
CoddyのHTMLジャーニー「JavaScript in Action」セクションの一部 — レッスン 19/27。
時には、要素がスクロール中にビューポートに入ったときに、アニメーション(フェードイン、スライドイン、ズームなど)をさせたいことがあります。
これは多くの場合、要素が画面内に表示されているかどうかを確認し、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未満であるかどうかをチェックします。 - 条件が真(true)の場合、
.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>このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。