ホームページ  >  記事  >  ウェブフロントエンド  >  HTML、CSS、JavaScript を使用してダーク モード切り替えを作成する方法

HTML、CSS、JavaScript を使用してダーク モード切り替えを作成する方法

WBOY
WBOYオリジナル
2024-08-29 15:00:26361ブラウズ

光か闇か?ワンクリックでテーマを切り替えてウェブサイトのアクセシビリティを向上

現在、Web サイトとアプリケーションには通常 2 つの異なるテーマがあります。1 つは日中の視認性を高めるための明るいテーマ、もう 1 つは夜間の目の疲れを軽減するための暗いテーマです。最高のエクスペリエンスを提供するには、Web サイトでユーザーが好みに基づいてこれらのテーマを簡単に切り替えられるようにする必要があります。この記事では、HTML、CSS、JavaScript を使用して Web サイトのダーク モード切り替えを作成し、ユーザーがワンクリックで明るいテーマと暗いテーマを切り替える方法を説明します。

このチュートリアルでは、明るいモードと暗いモードを表す太陽と月の切り替えボタンを作成します。ユーザーがボタンをクリックすると、Web サイトはこれら 2 つのモード間をスムーズに移行します。また、今後のアクセスに備えて、ユーザーのテーマ設定をローカル ストレージに保存します。

デモ、またはこの GitHub リポジトリ の完全なソース コードを参照してください。このステップバイステップのガイドで対話的に学習することも、下にスクロールして詳細なチュートリアルを表示することもできます。

前提条件

始める前に、次のものが揃っていることを確認してください。

  • HTML、CSS、JavaScript の基本的な知識
  • テキスト エディターまたは IDE (Visual Studio Code、Sublime Text など)
  • テスト用 Web ブラウザ

HTML構造のセットアップ

まず、基本的な HTML 構造を作成し、トグル ボタンとページ コンテンツを構築するために必要な要素を追加します。

1.新しい HTML ファイルを作成します。 テキスト エディタを開き、DOCTYPE、HTML、head、body タグなどの基本的な HTML 構造を含む新しい index.html ファイルを作成します。 ページにタイトル タグを追加し、外部 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.必要な要素を body に追加します。 body タグ内に、次の要素を追加します。

    すべてのコンテンツをラップするコンテナ 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 変数を定義します。これにより、後でテーマを簡単にカスタマイズできます。暗い色または明るい色を変更する場合は、1 か所で更新するだけで済みます。

/* 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 スタイルを使用すると、ページにデフォルトのライト テーマが設定されます。 Cursor: pointer プロパティにより、トグルがクリック可能であることが明確になります。

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

JavaScript 機能の実装

HTML 構造と CSS スタイルを設定したので、JavaScript を使用してダーク モードの切り替えにインタラクティブ機能を追加し、ユーザーの設定を記憶するローカル ストレージを実装します。

7. DOM 要素を選択します。 script.js ファイルを開き、変更する DOM 要素、トグル ボタンを含むテーマトグル 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。