首页 > web前端 > css教程 > 正文

如何使用 HTML、CSS 和 JavaScript 创建深色模式切换

WBOY
发布: 2024-08-29 15:00:26
原创
453 人浏览过

浅色还是深色?一键切换主题以实现网站无障碍

网站和应用程序现在通常有两个不同的主题:浅色主题可在白天提供更好的可视性,深色主题可减少夜间眼睛疲劳。为了提供最佳体验,您的网站应该允许用户根据自己的喜好在这些主题之间轻松切换。本文将指导您使用 HTML、CSS 和 JavaScript 为您的网站创建深色模式切换,使用户只需单击一下即可在浅色和深色主题之间切换。

在本教程中,我们将构建一个太阳和月亮切换按钮来代表明暗模式。当用户单击该按钮时,网站将在这两种模式之间平滑过渡。我们还将用户的主题偏好保存在本地存储中以供将来访问。

查看演示此 GitHub 存储库上的完整源代码。您可以通过此分步指南进行交互式学习,或向下滚动查看详细教程。

先决条件

在我们开始之前,请确保您已经:

  • HTML、CSS 和 JavaScript 的基础知识
  • 文本编辑器或 IDE(例如 Visual Studio Code、Sublime Text)
  • 用于测试的网络浏览器

设置 HTML 结构

首先,我们将创建基本的 HTML 结构并添加必要的元素来构建我们的切换按钮和页面内容。

1。创建一个新的 HTML 文件。 打开文本编辑器并创建一个新的index.html 文件,其中包含基本的 HTML 结构,包括 DOCTYPE、HTML、head 和 body 标签。 为页面添加标题标签导入外部 style.css script.js 文件.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Light/Dark Mode Toggle</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <script src="script.js"></script>
</body>
</html>
登录后复制

2。在正文中添加必要的元素。 在正文标记内,我们将添加以下元素:

  • 一个容器 div 来包装我们所有的内容
  • 页面的 h1 标题
  • 一个简短描述的p段
  • 一个切换容器 div,其中包含我们的切换开关
  • 太阳和月亮 SVG 图标
<body>
    <div class="container">
        <h1>Light/Dark Mode Toggle</h1>
        <p>Click the toggle below to switch between dark and light modes.</p>
        <div class="toggle-container" id="themeToggle">
            <svg class="sun-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="5"></circle>
                <line x1="12" y1="1" x2="12" y2="3"></line>
                <line x1="12" y1="21" x2="12" y2="23"></line>
                <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
                <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
                <line x1="1" y1="12" x2="3" y2="12"></line>
                <line x1="21" y1="12" x2="23" y2="12"></line>
                <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
                <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
            </svg>
            <svg class="moon-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
            </svg>
        </div>
    </div>
    <script src="script.js"></script>
</body>
登录后复制

这就是我们的普通 index.html 文件的样子:

How to Create a Dark Mode Toggle with HTML, CSS, and JavaScript

添加浅色和深色模式的 CSS 样式

在本节中,我们将设置 HTML 元素的样式并创建浅色和深色模式。我们还将使用过渡来实现平滑的颜色变化,并根据当前模式控制太阳和月亮图标的可见性。

3。定义浅色和深色的 CSS 变量。 在文本编辑器中打开 style.css 文件。我们将使用 :root 选择器定义深色和浅色的 CSS 变量。这允许稍后轻松定制主题。如果你想改变深色或浅色,只需要在一处更新即可。

/* Root selector for defining global CSS variables */
:root {
  --clr-dark: #333;  /* Dark color for text in light mode, background in dark mode */
  --clr-light: #fff; /* Light color for background in light mode, text in dark mode */
}
登录后复制

4。设置基本 CSS 样式。 为 body、.container 和 h1 元素添加样式以建立页面的布局和排版。您可以按照自己喜欢的方式自定义这些元素。

  • body 使用 CSS 颜色变量和平滑颜色变化的过渡将内容垂直和水平居中。
  • .container 将容器中的内容居中。
  • h1 在标题下方添加一些空格。
/* Base styles for the body */
body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: var(--clr-light);
    color: var(--clr-dark);
    transition: background-color 0.3s, color 0.3s;
}
/* Container for centering content */
.container {
    text-align: center;
}
/* Heading styles */
h1 {
    margin-bottom: 20px;
}
登录后复制

5。为深色模式添加 CSS 样式。 创建一个名为 .dark-mode 的 CSS 类,该类在应用于元素时交换背景和文本颜色。

/* Styles for dark mode */
.dark-mode {
    background-color: var(--clr-dark);
    color: var(--clr-light);
}
登录后复制

6。设置切换图标的样式。 为太阳和月亮 SVG 图标添加样式,并根据当前模式控制其可见性。

/* Styles for the toggle container */
.toggle-container {
    cursor: pointer;
}
/* Styles for the sun and moon icons */
.sun-icon, .moon-icon {
    width: 24px;
    height: 24px;
    transition: opacity 0.3s;
}
/* Hide moon icon by default (light mode) */
.moon-icon {
    display: none;
}
/* Show moon icon and hide sun icon in dark mode */
.dark-mode .sun-icon {
    display: none;
}
.dark-mode .moon-icon {
    display: inline-block;
}
登录后复制

使用这些 CSS 样式,您的页面将具有默认的浅色主题。光标:指针属性清楚地表明切换是可点击的。

How to Create a Dark Mode Toggle with HTML, CSS, and JavaScript

实现 JavaScript 功能

现在我们已经有了 HTML 结构和 CSS 样式,是时候使用 JavaScript 为我们的暗模式切换添加交互性并实现本地存储来记住用户的偏好了。

7。选择 DOM 元素。 打开 script.js 文件并选择我们要修改的 DOM 元素,即 themeToggle ID,其中包含我们的切换按钮。

const themeToggle = document.getElementById('themeToggle');
const body = document.body;
登录后复制

8. Add event listeners to the toggle button. This is the core functionality of the dark mode toggle. Add an event listener to the themeToggle element to detect when the user clicks on it. It will add the dark-mode class to the body element if it’s absent, or removes the class if present.

themeToggle.addEventListener('click', () => {
    body.classList.toggle('dark-mode');
});
登录后复制

At this point, the toggle switch is functional, and clicking on it will switch between light and dark modes. However, if you reload the page while in dark mode, the website will revert to its default light mode.

9. Save user theme preferences in local storage. To save the user's theme preference even after the browser is closed, we'll use the localStorage object. Inside the event listener callback function, it checks if the body element has the dark-mode class.

  • If it does, localStorage.setItem() saves the 'dark-mode' value to the 'theme' key.
  • If it doesn't, localStorage.setItem() saves an empty string to the 'theme' key.
themeToggle.addEventListener('click', () => {
    body.classList.toggle('dark-mode');

    // Store user preference in local storage
    if (body.classList.contains('dark-mode')) {
        localStorage.setItem('theme', 'dark-mode');
    } else {
        localStorage.setItem('theme', '');
    }
});
登录后复制

10. Check for a saved theme preference. When the page loads, we want to check if there's a saved theme preference in the local storage. Use localStorage.getItem() to retrieve the value associated with the 'theme' key. If a 'dark-mode' preference exists in the local storage, apply the dark mode theme immediately by adding the dark-mode class to the body element.

Note: Make sure to place the getItem() method before the event listener to ensure it runs on page load.

// Check if user preference exists in local storage
const currentTheme = localStorage.getItem('theme');
if (currentTheme) {
    body.classList.add(currentTheme);
}
登录后复制

The Dark Mode Toggle in Action

We've implemented all the necessary components for our dark mode toggle, so let's see it in action. Try clicking the toggle switch to see the smooth transition between light and dark themes. Refresh the page to verify your theme preference is remembered.

Check out the complete source code on this GitHub repository.

Tips for Dark Mode Implementation

Creating a dark mode toggle is just the beginning. To create a user-friendly dark mode experience, there are several best practices to keep in mind.

Tip #1: Choose the Right Colors for Dark Mode

Selecting colors for dark mode involves more than simply inverting your light theme. The goal is to create a contrast between text and background colors for readability. Use tools like color contrast checkers to verify that your chosen colors meet WCAG (Web Content Accessibility Guidelines) standards. Remember, a well-designed dark mode should be easy on the eyes and work well across devices.

Tip #2: Create a User-Friendly Toggle Button

Create a clear visual distinction between light and dark modes to help users identify each mode easily. Your toggle switch or button should clearly show the current mode. You can implement effective approaches such as a sun and moon icon toggle, which is used in this article and is an easily recognizable choice, a light and dark mode text button, or a sliding switch with light/dark mode labels. Whichever design you choose, make sure it's consistent with your user interface and provides clear feedback when the user interacts with it.

Tip #3: Implement Smooth Transitions

To create a more polished user experience, use CSS transitions or animations for a seamless shift between light and dark modes. Make sure that all elements, including images and icons, smoothly transition to the new color scheme. This can be done by adjusting opacity, brightness, or swapping out images for dark mode-specific versions.

Conclusion

Adding a dark mode toggle to your website greatly improves user experience. This is not just about aesthetics but also usability and accessibility. It allows users to view content comfortably based on their preferences and lighting conditions.

Throughout this article, we've walked through the process of creating a simple dark mode toggle, covering HTML structure, CSS styling for light and dark themes, JavaScript functionality, and storing user preference. The key is to keep it simple and user-friendly. Don't forget to test your dark mode thoroughly to ensure all elements remain readable and functional.

Now it's your turn to create your own dark mode toggle! Share your CodePen or GitHub link in the comments below.

Further Reading

Check out these resources to learn more about dark mode implementation and advanced techniques:

  • Dark theme - Material Design: Learn about dark mode implementation, anatomy, properties, and best practices from Material Design guidelines.
  • Top 20 CSS Toggle Switches [2024] - LambdaTest: Explore various CSS toggle switch designs for your website.

以上是如何使用 HTML、CSS 和 JavaScript 创建深色模式切换的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!