티스토리 뷰

반응형

1. HTML: 구조 잡기

체크박스(checkbox)를 활용하여 토글의 상태(On/Off)를 제어하는 구조입니다.

HTML
 
<!-- 토글 버튼 컨테이너 -->
<div class="toggle-container">
  <input type="checkbox" id="toggle-btn" class="toggle-input">
  <label for="toggle-btn" class="toggle-label">
    <span class="toggle-switch"></span>
  </label>
  <p id="status-text">현재 상태: OFF</p>
</div>

2. CSS: 스타일링 (디자인)

체크박스를 숨기고 label을 활용해 스위치 모양을 만듭니다.

CSS
 
/* 기본 컨테이너 설정 */
.toggle-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  font-family: sans-serif;
}

/* 실제 체크박스는 숨김 */
.toggle-input {
  display: none;
}

/* 스위치 배경 */
.toggle-label {
  width: 60px;
  height: 30px;
  background-color: #ccc;
  border-radius: 15px;
  display: block;
  position: relative;
  cursor: pointer;
  transition: background-color 0.3s;
}

/* 스위치 원형 버튼 */
.toggle-switch {
  width: 26px;
  height: 26px;
  background-color: white;
  border-radius: 50%;
  position: absolute;
  top: 2px;
  left: 2px;
  transition: transform 0.3s;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

/* 체크되었을 때(ON) 배경색 변경 */
.toggle-input:checked + .toggle-label {
  background-color: #4CAF50;
}

/* 체크되었을 때(ON) 버튼 이동 */
.toggle-input:checked + .toggle-label .toggle-switch {
  transform: translateX(30px);
}

반응형

3. JavaScript: 상태 제어

버튼의 변화를 감지하여 텍스트를 바꾸거나 특정 기능을 실행하게 합니다.

JavaScript
 
const toggleBtn = document.getElementById('toggle-btn');
const statusText = document.getElementById('status-text');

// 변경 이벤트 리스너 추가
toggleBtn.addEventListener('change', function() {
  if (this.checked) {
    statusText.innerText = "현재 상태: ON";
    statusText.style.color = "#4CAF50";
    // 여기에 ON일 때 실행할 함수 추가 (예: 다크모드 활성화)
  } else {
    statusText.innerText = "현재 상태: OFF";
    statusText.style.color = "#333";
    // 여기에 OFF일 때 실행할 함수 추가 (예: 다크모드 비활성화)
  }
});

💡 활용 팁

  • 다크 모드: 토글 버튼을 클릭했을 때 document.body.classList.toggle('dark-mode')를 실행하도록 설정하면 간단한 다크 모드 스위치가 됩니다.
  • 애니메이션: CSS의 transition 속성 값을 조절하면 스위치가 움직이는 속도를 부드럽게 바꿀 수 있습니다.

#HTML팁 #CSS디자인 #JavaScript활용 #토글버튼만들기 #웹개발기초 #프론트엔드 #코딩교육 #웹디자인

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/08   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함
반응형