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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| const btn = document.getElementById('toggleTheme');
function initTheme() { const theme = localStorage.getItem('theme'); if (theme === 'dark') { document.body.classList.add('dark'); btn.innerText = '🌙'; return; } if (theme === 'light') { btn.innerText = '🌞'; return; }
const isDark = window.matchMedia('(prefers-color-scheme: dark)'); if (isDark) document.body.classList.add('dark');
localStorage.setItem('theme', isDark ? 'dark' : 'light'); btn.innerText = isDark ? '🌙' : '🌞'; }
function toggleTheme() { console.log(`toggle theme`); document.body.classList.toggle('dark'); localStorage.setItem( 'theme', document.body.classList.contains('dark') ? 'dark' : 'light' ); btn.innerText = document.body.classList.contains('dark') ? '🌙' : '🌞'; }
window .matchMedia('(prefers-color-scheme: dark)') .addEventListener('change', (e) => { const newColorScheme = e.matches ? 'dark' : 'light'; localStorage.setItem('theme', newColorScheme);
if (newColorScheme === 'dark') { document.body.classList.add('dark'); btn.innerText = '🌙'; return; } document.body.classList.remove('dark'); btn.innerText = '🌞'; });
btn.addEventListener('click', function (event) { toggleTheme(); });
initTheme();
|