首頁 > web前端 > css教學 > 主體

如何使用 HTML、CSS 和 JavaScript 建立深色模式切換

WBOY
發布: 2024-08-29 15:00:26
原創
379 人瀏覽過

淺色還是深色?一鍵切換主題以實現網站無障礙

網站和應用程式現在通常有兩個不同的主題:淺色主題可在白天提供更好的可視性,深色主題可減少夜間眼睛疲勞。為了提供最佳體驗,您的網站應該允許用戶根據自己的喜好在這些主題之間輕鬆切換。本文將指導您使用 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學習者快速成長!