버튼 클릭 애니메이션
Coddy HTML 여정의 JavaScript 실전 섹션에 포함된 레슨. 27개 중 20번째.
때로는 버튼을 클릭했을 때 작아지거나, 빛나거나, 튀어 오르는 것처럼 즉각적인 피드백을 제공하기를 원합니다. JavaScript를 사용하여 CSS 애니메이션 또는 transition을 트리거할 수 있습니다.
먼저 HTML에서 간단한 버튼을 만드세요:
<button id="animatedButton">Click Me</button>그런 다음, 버튼의 스타일을 지정할 기본 CSS를 추가합니다.
#animatedButton {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: transform 0.2s, background-color 0.2s;
}이제 클릭 animation을 만들기 위해 JavaScript를 추가하세요:
const button = document.getElementById('animatedButton');
button.addEventListener('click', function() {
// Add a class for the click effect
button.classList.add('button-clicked');
// Remove the class after animation completes
setTimeout(function() {
button.classList.remove('button-clicked');
}, 200);
});마지막으로 animation effect를 위한 CSS를 추가합니다:
.button-clicked {
transform: scale(0.95);
background-color: #45a049;
}클릭하면 이제 button이 약간 작아지고 색상이 변경되어 사용자에게 시각적 피드백을 제공합니다.
챌린지
쉬움button을 Click하면 시각적 피드백을 위해 CSS class "button-clicked"를 button에 추가하세요.
이 class를 적용하는 줄을 click event listener 내부에 추가하세요.
직접 해보기
<!DOCTYPE html>
<html>
<head>
<title>Button Animation Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Interactive Button Demo</h1>
<p>Click the button below to see a smooth animation effect.</p>
</header>
<main class="content">
<button id="animatedButton" class="btn">Click Me</button>
</main>
<script src="script.js"></script>
</body>
</html>
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
JavaScript 실전의 모든 레슨
직접 연습해 보세요: Web 플레이그라운드