带有首选颜色方案的深色模式开关:深色

Mar*_*ark 3 javascript css jquery

我有一个用于启用暗模式的切换开关。

<div class="one-quarter d-flex justify-content-center" id="switch">
  <input type="checkbox" class="checkbox" id="chk" />
    <label class="switch-label" for="chk">
      <i class="fas fa-moon"></i>
      <i class="fas fa-sun"></i>
      <div class="ball"></div>
    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

通过一些 javascript,我可以为元素进行切换

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

chk.addEventListener('change', () => {

});
Run Code Online (Sandbox Code Playgroud)

然后将所有深色样式放入:

@media (prefers-color-scheme: dark) {

}
Run Code Online (Sandbox Code Playgroud)

如何使开关起作用以启用首选颜色方案:深色

小智 8

一个简单的方法是使用 CSS 变量,这样你就不必完全加载一个全新的 css 文件,而且它很流畅

 :root {
    --primary-color: #302AE6;
    --secondary-color: #536390;
    --font-color: #424242;
    --bg-color: #fff;
    --heading-color: #292922;
}

[data-theme="dark"] {
    --primary-color: #9A97F3;
    --secondary-color: #818cab;
    --font-color: #e1e1ff;
    --bg-color: #161625;
    --heading-color: #818cab;
}

body {
  background-color: var(--bg-color);
  color: var(--font-color);
  width: 100%;
}

h1 {
    color: var(--heading-color);
    font-family: "Sansita One", serif;
    font-size: 2rem;
    margin-bottom: 1vh;
}
Run Code Online (Sandbox Code Playgroud)

使用 JS 你可以切换它

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

chk.addEventListener('change', (e) => {
 if (e.target.checked) {
        document.documentElement.setAttribute('data-theme', 'dark');
    }
    else {        
      document.documentElement.setAttribute('data-theme', 'light');    
    }   
});

Run Code Online (Sandbox Code Playgroud)