CSS 트랜지션
Coddy HTML 여정의 JavaScript 실전 섹션에 포함된 레슨. 27개 중 18번째.
때때로 요소가 나타나거나 사라질 때 부드러운 애니메이션(fading, 슬라이딩 또는 크기 조정)을 만들고 싶을 수 있습니다.
이를 위해 CSS transition을 사용합니다(CSS mastery 섹션에서 다룹니다). JavaScript에서는 간단히 class를 추가하거나 제거하거나, 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을 클릭하면 - box가 페이드됩니다:
const button = document.getElementById("toggleBtn");
const box = document.getElementById("box");
button.addEventListener("click", function () {
// opacity fades
box.classList.toggle("hidden");
});챌린지
쉬움클릭하면 상자를 표시하거나 숨기는 Toggle 버튼을 만드세요.
단계:
- 다음을 저장할 두 개의 변수를 만드세요:
- Toggle 버튼 요소
- Fade 상자 요소
두 요소 모두에document.getElementById()를 사용하세요
- Toggle 버튼에 click 이벤트 리스너를 추가하세요
- 버튼을 클릭하면 Fade 상자 요소의 "hidden" class를 Toggle하세요
직접 해보기
<!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 플레이그라운드