如何使用CSS变量和本地存储的黑暗主题

199 阅读4分钟

使用CSS变量和本地存储的黑暗主题

暗色主题在今天的屏幕中已经获得了普遍性。在iOS、macOS、Windows和谷歌的这种趋势下,大多数系统都采用了黑暗主题。深色主题使你的网站更令人兴奋,对喜欢深色主题的用户更有吸引力。如果你包含在浅色和深色主题之间切换的功能,体验会变得更好。

这篇文章将帮助你学习如何使用CSS变量实现浅色和深色主题之间的切换功能。

前提条件

作为先决条件,读者必须对以下概念有良好的理解。

  • 具有HTML、SCSS和Javascript的基本知识。
  • 理解CSS的变量。

添加HTML

让我们开始建立我们将在教程中使用的HTML页面。我们将把theme 名称和switch id添加到复选框输入中,这样我们就需要在我们的javascript 中引用它。

我们将创建一个由容器组成的简单网页,在其中我们还将添加一个标题、一个切换按钮和一个段落,如下所示。

<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/main.css">
    <title>Adding dark theme to your site</title>
</head>
<body>
    <!-- container -->
    <div class="container">
        <!-- heading -->
        <h1>Section Engineering Education</h1>
        <!-- toggle switch contaner -->
        <div class="toggle-container">
            <input type="checkbox" id="switch" name="theme" /><label for="switch">Toggle</label>
        </div>
            <!-- close toggle switch container -->
            <!-- paragraph -->
        <p>Section partners with university students in Computer Science related fields of study to research and write about topics that are relevant to engineers in the modern technology landscape. You can find more information and program guidelines in the GitHub repository. If you're currently enrolled in a Computer Science related field of study and are interested in participating in the program, please complete <a href="https://docs.google.com/forms/d/e/1FAIpQLSfTbj3kqvEJEb5RLjqJurfbHa8ckzQx0CjRzaizblue9ZOK5A/viewform">this form </a></p>
            <!-- close paragraph -->
    </div>
       <!-- close container -->
    <script src="main.js"></script>
</body>
</html>

Output - HTML page

HTML页面

添加CSS

在与HTML文件相同的目录中,我们将添加CSS文件,用来将默认的 "浅色 "主题切换为 "深色 "主题。

我建议安装一个实时的SCSS编译器来实时编译我们的CSS代码。

你可以把颜色代码改为你喜欢的颜色,在深色和浅色主题中看起来都很有吸引力。

默认白色主题的CSS样式是。

/* default styling variables - making background color as white */
html{
    --bg: #fff;
    --bg-panel: #ebebeb;
    --color-heading: rgb(27, 168, 14); 
    --color-text: #333333;
}

深色主题的CSS样式是:。

/* dark theme styling - Here, we set data-them as "dark"*/
html[data-theme='dark'] {
    --bg: #333333;
    --bg-panel: #434343;
    --color-heading: #0077ff; 
    --color-text: #B5B5B5;
}

接下来,我们需要在CSS文件main.css ,指定CSS样式,这样,当我们点击切换主题按钮时,网站元素就会发生变化。

body { 
    background-color: var(--bg); /* background color variable */
}

.container {
  background-color: var(--bg-panel); /* background panel color variable */
  margin: 5em;
  padding: 5em;
  border-radius: 15px;
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: 80% auto;
      grid-template-columns: 80% auto;
  -ms-grid-rows: auto auto;
      grid-template-rows: auto auto;
      grid-template-areas: "title switch"
 "content content";
}

.container h1 {
  margin: 0;
  color: var(--color-heading); /* heading 1 background color variable */
}

.container p {
  color: var(--color-text); /* text-color variable */
  -ms-grid-column-span: 2;
  grid-area: content;
  font-size: 1.1em;
  line-height: 1.8em;
  margin-top: 2em;
}

Output After Adding CSS

添加CSS样式后的输出

切换主题

在下一节中,我们将为我们的 "切换开关 "设计样式,它将帮助我们在深色和浅色主题之间切换。切换按钮的代码如下所示。

input[type=checkbox] { /* styling for input element */
    height: 0;
    width: 0;
    visibility: hidden;
}

label { /* styling for labels */
    cursor: pointer;
    text-indent: -9999px;
    width: 52px;
    height: 27px;
    background: #1ba80e;
    float: right;
    border-radius: 100px;
    position: relative;
}

label:after { /* styling for labels - on toggle */
    content: '';
    position: absolute;
    top: 3px;
    left: 3px;
    width: 20px;
    height: 20px;
    background: #fff;
    border-radius: 90px;
    -webkit-transition: 0.3s;
    transition: 0.3s;
}

input:checked + label { /* conditional check while toggling */
    background: var(--color-heading);
}

input:checked + label:after {
    left: calc(100% - 5px);
    -webkit-transform: translateX(-100%);
            transform: translateX(-100%);
}

label:active:after {
    width: 45px;
}

Toggle theme switch

切换主题

添加JavaScript

我们将用JavaScript来处理主题切换,方法是将切换开关的类名改为lightdark ,定义如下。在这样做的时候,我们写两个函数changeThemeToDark()chnageThemeToWhite()

将主题改为深色

// Change theme to dark by adding the `dark` classname to html element.
const changeThemeToDark = () => {
    document.documentElement.setAttribute("data-theme", "dark")//set theme to light
}

将主题改为浅色

// Reset the html class to default
const changeThemeToDark = () => {
    document.documentElement.setAttribute("data-theme", "light"); //set theme to light
}

使用本地存储

本地存储为浏览器中的键和值对提供了一个存储。使用本地存储的数据存储即使在浏览器关闭或刷新后也不会过期。

setItemgetItem 方法分别用来存储和检索存储的数据。

我们将使用本地存储来存储我们当前设置的主题,这样在随后的访问或页面刷新中,用户将看到他们之前设置的主题。

下面这段代码是用来保存和检索本地存储的主题的。

let theme = localStorage.getItem('data-theme');
const changeThemeToDark = () => {
    document.documentElement.setAttribute("data-theme", "dark") // set theme to dark
    localStorage.setItem("data-theme", "dark") // save theme to local storage
}

const changeThemeToLight = () => {
    document.documentElement.setAttribute("data-theme", "light") // set theme light
    localStorage.setItem("data-theme", 'light') // save theme to local storage
}

写完这些函数后,我们将检查当前设置的主题,并将其切换。

// Get the element based on ID
const checkbox = document.getElementById("switch");
// Apply retrived them to the website
checkbox.addEventListener('change', () => {
    let theme = localStorage.getItem('data-theme'); // Retrieve saved them from local storage
    if (theme ==='dark'){
        changeThemeToLight()
    }else{
        changeThemeToDark()
    }   
});

Dark Theme

黑暗主题网页

总结

这篇文章已经解释了我们如何通过使用CSS变量和localStorage来实现深色和浅色主题,并切换它们。