0

Добавить/удалить setAttribute получилось. Но как сохранить атрибут у body при перезагрузке страницы?

Вот мой код:

document.getElementById('switch').onclick = function () {
if(document.body.hasAttribute('data-theme', 'dark')){
    document.body.removeAttribute('data-theme', 'dark');
    localStorage.removeItem('data-theme');
} else {
    document.body.setAttribute('data-theme', 'dark');
    localStorage.setItem('data-theme', 'dark');


    let darkmode = localStorage.getItem('data-theme');
    darkmode = darkmode ? JSON.parse(darkmode) : {};
    darkmode['data-theme'] = 'dark';

    localStorage.setItem('data-theme', JSON.stringify(darkmode));
}
};
1
  • 3
    Вам нужно, чтобы при рендере станицы, происходила проверка localStorage пользователя на наличие там data-theme, и если значение есть, то в body передавалось это значение, а если нет, то выставлялось по умолчанию? 9 янв 2020 в 8:46

1 ответ 1

0

Решение:

let key = 'data-theme';
let value = 'dark';
let theme = localStorage.getItem(key);

if (theme) {
 document.body.setAttribute(key, theme);
}

document.getElementById('switch').onclick = function () {
if(document.body.hasAttribute(key, value)){
    document.body.removeAttribute(key, value);
    localStorage.removeItem(key);
} else {
    document.body.setAttribute(key, value);
    localStorage.setItem(key, value);
}
};

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.