Приведенный ниже код работает, но я не уверен, правильно ли он написан или существует более лучший/чистый подход.
В частности, я хотел бы знать:
- Правильна ли моя логика для сохранения выбранной темы после обновить?
- Как это можно написать более удобным или идиоматическим способом?
const input = document.querySelector('input')
let currentTheme = ''
document.body.classList.add(localStorage.getItem('theme'))
input.addEventListener('click', function () {
if (localStorage.getItem('theme') === 'dark') {
currentTheme = 'light'
localStorage.setItem('theme', currentTheme)
document.body.classList.remove('dark')
document.body.classList.add(currentTheme)
} else {
currentTheme = 'dark'
localStorage.setItem('theme', currentTheme)
document.body.classList.remove('light')
document.body.classList.add(currentTheme)
}
})
Подробнее здесь: https://stackoverflow.com/questions/797 ... ge-refresh
Мобильная версия