Полное решение:
CSS:
:root {
--bg: #ffffff;
--text: #1a1a1a;
}
[data-theme="dark"] {
--bg: #1a1a1a;
--text: #f5f5f5;
}
body {
background: var(--bg);
color: var(--text);
transition: background 0.3s, color 0.3s;
}
JS:
const toggle = document.getElementById('theme-toggle');
// Проверяем сохраненную тему или системные настройки
const getPreferredTheme = () => {
const saved = localStorage.getItem('theme');
if (saved) return saved;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
};
// Применяем тему
const setTheme = (theme) => {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
};
// Инициализация
setTheme(getPreferredTheme());
// Переключение
toggle.addEventListener('click', () => {
const current = document.documentElement.getAttribute('data-theme');
setTheme(current === 'dark' ? 'light' : 'dark');
});
Атрибут data-theme вешается на html, localStorage сохраняет выбор между сессиями, matchMedia проверяет системные настройки при первом визите.
Работает идеально, спасибо. Единственное - добавил проверку на null в getPreferredTheme чтобы линтер не ругался