スクロールで要素をアニメーション
CoddyのHTMLジャーニー「JavaScriptの実践」セクションの一部。レッスン 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文を作成します。
- 条件では、要素の上端の位置が
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>このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
JavaScriptの実践のすべてのレッスン
自分で練習してみよう: Webプレイグラウンド