CSS 트랜지션
Coddy HTML 여정의 JavaScript 실전 섹션에 포함된 레슨. 27개 중 18번째.
요소가 나타나거나 사라질 때 페이드, 슬라이드, 크기 조절과 같은 부드러운 애니메이션을 만들고 싶을 때가 있습니다.
이를 위해 CSS 전환을 사용합니다(CSS 숙달 섹션에서 다룹니다). JavaScript에서는 클래스를 추가하거나 제거하고, 스타일 속성을 수정하기만 하면 됩니다.
HTML:
<button id="toggleBtn">Toggle Box</button>
<div id="box" class="box"></div>.box의 불투명도에는 전환 효과가 적용되어 있으므로, .hidden 클래스가 추가되면(불투명도를 0으로 설정함) 상자가 즉시 사라지는 대신 서서히 사라집니다.
.box {
width: 100px;
height: 100px;
background-color: teal;
transition: opacity 0.5s ease; /* 클래스 전환용 */
opacity: 1;
}
.hidden {
opacity: 0;
}버튼을 클릭하면 상자가 서서히 사라집니다:
const button = document.getElementById("toggleBtn");
const box = document.getElementById("box");
button.addEventListener("click", function () {
// 불투명도가 서서히 낮아짐
box.classList.toggle("hidden");
});챌린지
쉬움클릭하면 상자를 표시하거나 숨기는 토글 버튼을 만드세요.
단계:
- 다음을 저장할 변수 두 개를 만드세요:
- 토글 버튼 요소
- 페이드 상자 요소
두 요소 모두에document.getElementById()를 사용하세요.
- 토글 버튼에 클릭 이벤트 리스너를 추가하세요.
- 버튼을 클릭하면 페이드 상자 요소의 "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 플레이그라운드