CSS 트랜지션
Coddy HTML 여정의 JavaScript in Action 섹션에 포함된 레슨 — 27개 중 18번째.
때때로 우리는 요소가 나타나거나 사라질 때 부드러운 애니메이션(페이딩, 슬라이딩 또는 크기 조정과 같은)을 만들고 싶어 합니다.
이를 위해 CSS 트랜지션(CSS 마스터 섹션에서 다룸)을 사용합니다. JavaScript에서는 단순히 클래스를 추가하거나 제거하거나, 스타일 속성을 수정합니다.
HTML:
<button id="toggleBtn">Toggle Box</button>
<div id="box" class="box"></div>.box는 opacity에 트랜지션이 설정되어 있어, .hidden 클래스가 추가되면(opacity를 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>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.