반응형
SMALL
📌 개요
HTML, CSS, JavaScript를 활용하여 디지털 모래시계 타이머를 구현합니다. 사용자가 버튼을 클릭하면 모래가 흘러내리는 애니메이션과 함께 타이머가 시작되며, 시간이 끝나면 알림을 출력하는 기능이 포함됩니다.
📌 구현 기능
- 버튼을 클릭하면 타이머 시작
- 모래가 점점 차오르는 애니메이션 효과 적용
- 타이머 종료 시 메시지 출력
- JavaScript의 setInterval()을 활용하여 시간 감소
📌 HTML 구조
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>디지털 모래시계</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f4f4f4;
margin-top: 50px;
}
.sand-timer {
position: relative;
width: 100px;
height: 150px;
border: 4px solid #333;
border-radius: 10px;
margin: 20px auto;
overflow: hidden;
background: #fff;
}
.sand {
position: absolute;
bottom: 0;
width: 100%;
height: 0;
background: goldenrod;
transition: height 1s linear;
}
.timer-text {
font-size: 20px;
margin-top: 10px;
}
button {
padding: 10px 15px;
font-size: 16px;
border: none;
background: #007bff;
color: white;
border-radius: 5px;
cursor: pointer;
margin-top: 10px;
}
button:hover {
background: #0056b3;
}
</style>
</head>
<body>
<h2>⏳ 디지털 모래시계</h2>
<div class="sand-timer">
<div class="sand" id="sand"></div>
</div>
<p class="timer-text" id="timerText">10초 남음</p>
<button id="startTimer">타이머 시작</button>
<script>
document.addEventListener("DOMContentLoaded", () => {
const sand = document.getElementById("sand");
const timerText = document.getElementById("timerText");
const startButton = document.getElementById("startTimer");
let timeLeft = 10;
let timer;
function startSandTimer() {
sand.style.height = "100%"; // 모래가 점점 차오름
startButton.disabled = true; // 버튼 비활성화
timer = setInterval(() => {
timeLeft--;
timerText.textContent = `${timeLeft}초 남음`;
if (timeLeft <= 0) {
clearInterval(timer);
timerText.textContent = "시간 종료!";
startButton.disabled = false;
sand.style.height = "0"; // 다시 초기화
}
}, 1000);
}
startButton.addEventListener("click", startSandTimer);
});
</script>
</body>
</html>
📌 코드 설명
✅ 1. HTML & CSS 구성
- sand-timer: 모래시계 컨테이너
- sand: 모래 애니메이션 영역
- timer-text: 타이머 텍스트 표시
- button: 타이머 시작 버튼
✅ 2. JavaScript 기능
- setInterval()을 사용하여 초 단위 감소
- 모래 높이를 증가시키며 시각적 애니메이션 효과 적용
- 시간이 끝나면 clearInterval()로 타이머 정지 및 초기화
📌 마무리 🎯
- setInterval()을 활용하여 카운트다운 구현
- CSS 애니메이션을 활용하여 시각적인 효과 추가
- 타이머가 종료되면 초기 상태로 복구 가능
반응형
LIST
'Javascript' 카테고리의 다른 글
[Dseok의 코딩스터디] JavaScript slice() vs splice() 차이점 한방에 끝내기 (1) | 2025.03.06 |
---|---|
[Dseok의 코딩스터디] JavaScript slice() 한방에 끝내기 | 개념 & 실전 예제 10가지 (0) | 2025.03.05 |
[Dseok의 코딩스터디] JavaScript로 랜덤 얼굴 생성기 구현하기 (0) | 2025.03.03 |
[Dseok의 코딩스터디] JavaScript로 간단한 채팅봇 만들기 (1) | 2025.03.02 |
[Dseok의 코딩스터디] JavaScript map() 한방에 끝내기 | 개념 & 실용 예제 10가지 (0) | 2025.03.01 |