保存暗模式复选框切换到本地存储

时间:2020-10-11 06:23:39

标签: javascript html css web local-storage

在我的网站上,我有一个复选框,可以在默认的浅色主题和深色的主题之间切换。如果页面设置为暗模式并刷新,则主题将切换回亮模式。有没有一种方法可以保存访问者的决定,以便刷新时页面保持在暗模式下?这是我目前拥有的代码:

const chk = document.getElementById('chk');

chk.addEventListener('change', () => {
    document.body.classList.toggle('dark');
});
body {
  background: #f5f5f5;
  color: #353535;
}

body.dark {
  background-color: #1a1a1a;
  color: #f5f5f5;
}
        <div class="toggle">
            <input type="checkbox" class="checkbox" id="chk" />
            <label class="label" for="chk">
        </div>
        <h1>website text</h1>

我意识到这可能是一个简单的答案,但是我对Web开发是陌生的,并且正在努力寻找自己的答案。预先感谢您的所有帮助。

5 个答案:

答案 0 :(得分:1)

localStorage sessionStorage 属性允许将key/value对保存在网络浏览器中。

localStorage 对象存储的数据具有无失效日期。当浏览器被关闭时,数据将不会被删除,并且在第二天,每周或每年都可用。


要存储值,请选中复选框以存储在本地存储中。每当打开页面以检查是否存储值时。

您的案例,您可以尝试....

StackOverflow代码段注释存储localStorage,因此请将此代码复制到您的文件中。


const toggleSwitch = document.querySelector('input[type="checkbox"]');
const currentTheme = localStorage.getItem('theme');

if (currentTheme) {
    document.documentElement.setAttribute('data-theme', currentTheme);
  
    if (currentTheme === 'dark') {
        toggleSwitch.checked = true;
         document.body.classList.toggle('dark');
    }
}

function switchTheme(e) {
    if (e.target.checked) {
        document.documentElement.setAttribute('data-theme', 'dark');
        localStorage.setItem('theme', 'dark');
         document.body.classList.toggle('dark');
    }
    else {        document.documentElement.setAttribute('data-theme', 'light');
          localStorage.setItem('theme', 'light');
           document.body.classList.toggle('dark');
    }    
}

toggleSwitch.addEventListener('change', switchTheme, false);
body {
    background: #f5f5f5;
    color: #353535;
}

body.dark {
    background-color: #1a1a1a;
    color: #f5f5f5;
}
<div class="toggle">
    <input type="checkbox" class="checkbox" id="chk" />
    <label class="label" for="chk">
</div>
<h1>website text</h1>

答案 1 :(得分:0)

一个非常简单的例子。使用localStorage.setItem()将值存储在本地存储中。您可以使用任何方法从输入中检索数据。在这里,我只是使用一种表格。

function toggleDarkMode() {
  const formElem = document.getElementById('dark-mode');
  const formData = new FormData(formElem);
  const darkModeState = !!formData.get('toggler');
  localStorage.setItem('darkMode', darkModeState);
}
<form id="dark-mode">
  <input type="checkbox" name="toggler"> Use darkmode
  <br/>
  <button type="button" onClick="toggleDarkMode()">Save</button>
</form>

答案 2 :(得分:0)

首先定义一个变量,然后将localstorage定义为它的值(最好在设置该值之前检查本地存储):

FROM alpine:latest
MAINTAINER SURF Team "davide.vanzo@eawag.ch"

# get the tools we need
RUN apk update && apk add gfortran \
    musl-dev bash python py-pip doxygen git graphviz

RUN pip install FoBiS.py ford pygooglechart

# root dir
RUN mkdir /home/Simstrat
WORKDIR /home/Simstrat

# calls that are needed to build and start the container with the build environment:
# docker build -t simstrat:alpine .
# docker create --name simstrat -it -v <pathToLocalGitRepoDirectory>:/home/Simstrat simstrat:alpine
# docker start simstrat
# docker exec -it simstrat bash

然后在用户选中复选框时将其设为true 并在本地存储中更新

let DarkMode = localStorage.getItem('DarkMode');
if(DarkMode == null) {
   localStorage.setItem('DarkMode', 'false');
}
let DarkMode = localStorage.getItem('DarkMode');
if(DarkMode == null) {
   localStorage.setItem('DarkMode', 'false');
}

const chk = document.getElementById('chk');

chk.addEventListener('change', () => {
    document.body.classList.toggle('dark');
    if (DarkMode == false) {
       DarkMode = true;
       localStorage.setItem('DarkMode' , true)
       console.log(DarkMode);
    } else {
       DarkMode = false;
       localStorage.setItem('DarkMode' , false)
       console.log(DarkMode);
    }
});
body {
  background: #f5f5f5;
  color: #353535;
}

body.dark {
  background-color: #1a1a1a;
  color: #f5f5f5;
}

答案 3 :(得分:0)

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
  background: #f5f5f5;
  color: #353535;
  text-align:right;
}

body.dark {
  background-color: #1a1a1a;
  color: #f5f5f5;
}
</style>

<title>Dark mode to Local Storage</title>
</head>
<body>

        <div class="toggle">
            <input type="checkbox" class="checkbox" id="chk" />
            <label class="label" for="chk">Turn On Dark Mode</label>
        </div>
        <h1>Website Content</h1>
        
<script>
const chk = document.getElementById('chk');

chk.addEventListener('click', () => {
  chk.checked?document.body.classList.add("dark"):document.body.classList.remove("dark");
  localStorage.setItem('darkModeStatus', chk.checked);
});

window.addEventListener('load', (event) => {
  if(localStorage.getItem('darkModeStatus')=="true"){
    document.body.classList.add("dark"); 
    document.getElementById('chk').checked = true;
  }
});
</script>        
</body>
</html>

答案 4 :(得分:-1)

let darkMode = false;

如果用户选中将变量更改为true 然后在本地存储中设置变量。

LocalStorage.setItem('darkTheme',true);

然后使用localStorage.getItem(darkTheme')

获取变量