CSSトランジション
CoddyのHTMLジャーニー「JavaScriptの実践」セクションの一部。レッスン 18/27。
要素が表示されたり消えたりするときに、滑らかなアニメーション(フェード、スライド、サイズ変更など)を作成したい場合があります。
そのために CSS の transition を使用します(CSS mastery セクションで扱います)。JavaScript では、単にクラスを追加または削除するか、style プロパティを変更します。
HTML:
<button id="toggleBtn">Toggle Box</button>
<div id="box" class="box"></div>.box には opacity の transition が設定されているため、.hidden class が追加されると(opacity が 0 に設定されるため)、box は即座に消えるのではなく、徐々に消えていきます。
.box {
width: 100px;
height: 100px;
background-color: teal;
transition: opacity 0.5s ease; /* for class toggle */
opacity: 1;
}
.hidden {
opacity: 0;
}button が click されると - box が fades:
const button = document.getElementById("toggleBtn");
const box = document.getElementById("box");
button.addEventListener("click", function () {
// opacity fades
box.classList.toggle("hidden");
});チャレンジ
簡単クリックするとボックスを表示/非表示にする Toggle ボタンを作成します。
手順:
- 次の要素を格納する2つの変数を作成します:
- Toggle ボタン要素
- フェードボックス要素
両方にdocument.getElementById()を使用します
- Toggle ボタンにクリックイベントリスナーを追加します
- ボタンがクリックされたとき、フェードボックス要素の "hidden" クラスを切り替えます
自分で試してみよう
<!DOCTYPE html>
<html>
<head>
<title>Fade Toggle Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Smooth Fade Example</h1>
<p>Click the button below to toggle the fading box.</p>
<button id="toggleBtn">Toggle Box</button>
<div id="fadeBox" class="box">
<p>This box fades in and out smoothly!</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
JavaScriptの実践のすべてのレッスン
自分で練習してみよう: Webプレイグラウンド