반응형
안녕하세요! 오늘은 웹사이트에서 사용자가 직접 다크모드, 라이트모드, 시스템 모드를 선택할 수 있는 방법을 알려드리겠습니다.
3가지 모드 다크모드 토글 버튼이란?
사용자가 직접 버튼을 클릭하여 "System(시스템 설정 반영)", "Dark(강제 다크모드)", "Light(강제 라이트모드)" 세 가지 중 원하는 모드를 선택할 수 있습니다. 또한 이 설정은 사용자의 기기에 저장되어 다음 접속 때도 유지됩니다.
HTML, CSS, JavaScript 코드
아래의 코드로 간단히 구현 가능합니다.
<button class="dark-button">모드: System (Light)</button>
html {
background-color: #ffffff;
color: #000000;
transition: background-color 0.3s, color 0.3s;
}
@media (prefers-color-scheme: dark) {
html {
background-color: #222222;
color: #ffffff;
}
}
.dark-mode {
background-color: #222222 !important;
color: #ffffff !important;
}
.light-mode {
background-color: #ffffff !important;
color: #000000 !important;
}
document.addEventListener("DOMContentLoaded", function() {
const button = document.querySelector('.dark-button');
const htmlEl = document.documentElement;
const savedTheme = localStorage.getItem('theme') || 'system';
applyTheme(savedTheme);
updateButtonText(savedTheme);
button.addEventListener('click', function() {
let currentTheme = localStorage.getItem('theme') || 'system';
let newTheme;
if (currentTheme === 'system') newTheme = 'dark';
else if (currentTheme === 'dark') newTheme = 'light';
else newTheme = 'system';
localStorage.setItem('theme', newTheme);
applyTheme(newTheme);
updateButtonText(newTheme);
});
function applyTheme(theme) {
htmlEl.classList.remove('dark-mode', 'light-mode');
if (theme === 'dark') htmlEl.classList.add('dark-mode');
else if (theme === 'light') htmlEl.classList.add('light-mode');
}
function updateButtonText(theme) {
if (theme === 'system') {
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? 'Dark' : 'Light';
button.textContent = "모드: System (" + systemTheme + ")";
} else {
button.textContent = "모드: " + theme.charAt(0).toUpperCase() + theme.slice(1);
}
}
window.matchMedia("(prefers-color-scheme: dark)").addEventListener('change', () => {
if ((localStorage.getItem('theme') || 'system') === 'system') updateButtonText('system');
});
});
마무리
이제 여러분의 웹사이트에서도 손쉽게 사용자 맞춤형 다크모드를 제공할 수 있습니다.
반응형