Color Scheme Switcher - Pure JS
помогите мне с кодом ниже, как сделать, чтобы после перезапуска страницы цвет остался прежним?
document.getElementById('grayButton').onclick = switchGray;
document.getElementById('whiteButton').onclick = switchWhite;
document.getElementById('blueButton').onclick = switchBlue;
document.getElementById('yellowButton').onclick = switchYellow;
function switchGray() {
document.getElementsByTagName('body')[0].style.backgroundColor = 'gray';
document.getElementsByTagName('body')[0].style.color = 'white';
}
function switchWhite() {
document.getElementsByTagName('body')[0].style.backgroundColor = 'white';
document.getElementsByTagName('body')[0].style.color = 'black';
}
function switchBlue() {
document.getElementsByTagName('body')[0].style.backgroundColor = 'blue';
document.getElementsByTagName('body')[0].style.color = 'white';
}
function switchYellow() {
document.getElementsByTagName('body')[0].style.backgroundColor = 'yellow';
document.getElementsByTagName('body')[0].style.color = 'black';
}
body {
margin: 3em;
padding: 0;
font-family: sans-serif;
font-size: 18px;
line-height: 1.5;
}
#switcher {
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
}
#switcher li {
float: left;
width: 30px;
height: 30px;
margin: 0 15px 15px 0;
border-radius: 30px;
border: 3px solid black;
}
#grayButton {
background: gray;
}
#whiteButton {
background: white;
}
#blueButton {
background: blue;
}
#yellowButton {
background: yellow;
}
<ul id="switcher">
<li id="grayButton"></li>
<li id="whiteButton"></li>
<li id="blueButton"></li>
<li id="yellowButton"></li>
</ul>
Ответы (1 шт):
Прикладываю код решения задачи, в песочнице SO он работать не будет.
Но будет работать на JSFIDDLE.
Немного объясню логику скрипта.
В начале мы задаем объект, содержащий все наши темы.
Затем мы выбираем элемент к которому будем цеплять наш класс, по умолчанию это
bodyПосле этого мы возьмем значение темы из локального хранилища и установим его в качестве темы по умолчанию
Если тема в локальном хранилище будет недоступна/удалена/не задана, то по умолчанию сработает тема
gray.Теперь применяем нашу тему на указанном элементе
Выбираем все элементы содержащие атрибут
data-themeи вешаем на них событиеclickВ обработчике
switchThemeHandleмы проверяем наличие темы из заданного объектаСбрасываем все темы что были установлены до этого с помощью
regex'aУстанавливаем указанную тему и сохраняем значение в
localStorage
// Объект содержащий все темы
const themes = {
gray: 'theme--gray',
red: 'theme--red',
green: 'theme--green',
blue: 'theme--blue'
}
// Выбираем элемент у которого будет изменяться класс.
const themeElement = document.body;
// Берем название темы из локального хранилища
const themeFromStorage = localStorage.getItem('theme');
// Создаем тему по умолчанию, если тема не найдена, сработает условие.
const defaultTheme = themes[themeFromStorage] || themes.gray;
// Устанавливаем тему по умолчанию.
themeElement.classList.add(defaultTheme);
// Выбираем все элементы у которых есть аттрибут data-theme.
const themeSwitchers = document.querySelectorAll('[data-theme]');
// Перебираем все элементы и вешаем на них событие отслеживающее нажатие.
for (const switcher of themeSwitchers)
switcher.addEventListener('click', switchThemeHandle);
// Обработчик смены тем
function switchThemeHandle(e) {
// Получаем значение дата аттрибута
const { theme } = e.target.dataset;
// Проверяем, есть ли в заданном массиве тем, наша новая тема
if (!Object.keys(themes).includes(theme)) {
console.error('Ошибка смены темы. Тема не найдена.');
return;
}
// Удаляем все старые темы по условию
themeElement.className = themeElement.className.replace(/([theme\-\-]+[a-z]+)/, '');
// Добавляем новую тему
themeElement.classList.add(themes[theme]);
// Сохраняем тему в локальное хранилище
localStorage.setItem('theme', theme);
}
.themes {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
display: flex;
}
.themes > * {
margin: 0 10px;
}
.themes button {
padding: 12px 24px;
border-width: 1px;
border-style: solid;
outline: none;
color: #fff;
cursor: pointer;
}
.themes .gray { background-color: #95a5a6; border-color: #7f8c8d; }
.themes .red { background-color: #e74c3c; border-color: #c0392b; }
.themes .green { background-color: #2ecc71; border-color: #27ae60; }
.themes .blue { background-color: #3498db; border-color: #2980b9; }
.themes .unknown { background-color: #9b59b6; border-color: #8e44ad; }
body.theme--gray { background-color: #95a5a6; }
body.theme--red { background-color: #e74c3c; }
body.theme--green { background-color: #2ecc71; }
body.theme--blue { background-color: #3498db; }
<div class="themes">
<button class="gray" data-theme="gray">GRAY</button>
<button class="red" data-theme="red">RED</button>
<button class="green" data-theme="green">GREEN</button>
<button class="blue" data-theme="blue">BLUE</button>
<button class="unknown" data-theme="unknown">unknown</button>
</div>