↓↓↓ クリックしてみてね ↓↓↓
Box-Area
「クリック」ボタンがクリックされると、.box 要素が赤く拡大し、1秒後に元の青い状態に戻るシンプルなアニメーションを実現しています。このアニメーションは、CSSのトランジションを使用してスムーズに実行され、JavaScriptが要素のスタイルを変更することでトリガーされます。
目次
HTML (index.html):
HTMLファイルは、基本的な構造を持つウェブページを定義しています。<div> 要素と <button> 要素が中央に配置されています。
ページのヘッダーで、文字エンコーディングとビューポート設定を指定し、外部のCSSファイル(styles.css)とJavaScriptファイル(script.js)を読み込んでいます。
CSS (style.css):
CSSファイルは、.box クラスにスタイルを適用しています。
.box クラスは、幅と高さを100pxに設定し、背景色を青に設定します。
transition プロパティを使用して、幅、高さ、背景色の変更が1秒かけてアニメーション化されるように設定されています。
JavaScript (script.js):
JavaScriptファイルでは、getElementById メソッドを使用して、HTMLから要素を取得しています。
animateButton ボタンがクリックされたときに、click イベントリスナーが呼び出され、アニメーションが開始されます。
box 要素の幅、高さ、背景色が変更され、これによりアニメーションがトリガーされます。
setTimeout 関数を使用して、1秒後に要素のスタイルを元に戻すコードが実行されます。
コード
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Transitions</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<br>
<center><div class="box" id="animated-box">Box-Area</div></center>
<br>
<center><button id="animate-button">クリック</button></center>
<script src="script.js"></script>
</body>
</html>
.box {
width: 100px;
height: 100px;
background-color: blue;
transition: width 1s, height 1s, background-color 1s;
text-align: center;
line-height: 100px;
color: white;
cursor: pointer;
}
const box = document.getElementById('animated-box');
const animateButton = document.getElementById('animate-button');
animateButton.addEventListener('click', () => {
box.style.width = '200px';
box.style.height = '200px';
box.style.backgroundColor = 'red';
setTimeout(() => {
box.style.width = '100px';
box.style.height = '100px';
box.style.backgroundColor = 'blue';
}, 1000);
});
