Rumah  >  Artikel  >  hujung hadapan web  >  Cara Membuat Togol Mod Gelap dengan HTML, CSS dan JavaScript

Cara Membuat Togol Mod Gelap dengan HTML, CSS dan JavaScript

WBOY
WBOYasal
2024-08-29 15:00:26360semak imbas

Terang atau Gelap? Pertukaran Tema Satu Klik untuk Kebolehcapaian Laman Web

Tapak web dan aplikasi kini biasanya mempunyai dua tema yang berbeza: tema terang untuk keterlihatan yang lebih baik pada waktu siang dan tema gelap untuk mengurangkan ketegangan mata pada waktu malam. Untuk memberikan pengalaman terbaik, tapak web anda harus membenarkan pengguna bertukar-tukar antara tema ini dengan mudah berdasarkan pilihan mereka. Artikel ini akan membimbing anda membuat togol mod gelap untuk tapak web anda menggunakan HTML, CSS dan JavaScript, membolehkan pengguna bertukar antara tema terang dan gelap dengan satu klik.

Dalam tutorial ini, kami akan membina butang togol matahari dan bulan untuk mewakili mod terang dan gelap. Apabila pengguna mengklik butang, tapak web akan lancar beralih antara dua mod ini. Kami juga akan menyimpan pilihan tema pengguna dalam storan setempat untuk lawatan akan datang.

Lihat demo atau kod sumber lengkap pada repositori GitHub ini. Anda boleh belajar secara interaktif dengan panduan langkah demi langkah ini atau tatal ke bawah untuk mendapatkan tutorial terperinci.

Prasyarat

Sebelum kami bermula, pastikan anda mempunyai:

  • Pengetahuan asas HTML, CSS dan JavaScript
  • Editor teks atau IDE (cth., Kod Visual Studio, Teks Sublime)
  • Pelayar web untuk ujian

Menyediakan Struktur HTML

Pertama, kami akan mencipta struktur HTML asas dan menambah elemen yang diperlukan untuk membina butang togol dan kandungan halaman kami.

1. Cipta fail HTML baharu. Buka editor teks anda dan buat index.html fail baharu dengan struktur HTML asas, termasuk DOCTYPE, HTML, teg kepala dan badan. Tambahkan teg tajuk untuk halaman dan import luaran style.css dan script.js fail.

<!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. Tambahkan elemen yang diperlukan pada badan. Di dalam teg badan, kami akan menambah elemen berikut:

  • Div kontena untuk membungkus semua kandungan kami
  • Tajuk h1 untuk halaman
  • Perenggan p untuk penerangan ringkas
  • Div bekas togol yang akan menyertakan suis togol kami
  • Ikon SVG matahari dan bulan
<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>

Beginilah rupa fail index.html biasa kami:

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

Menambah Penggayaan CSS untuk Mod Cerah dan Gelap

Dalam bahagian ini, kami akan menggayakan elemen HTML kami dan mencipta mod terang dan gelap. Kami juga akan menggunakan peralihan untuk perubahan warna yang lancar dan mengawal keterlihatan ikon matahari dan bulan berdasarkan mod semasa.

3. Tentukan pembolehubah CSS untuk warna terang dan gelap. Buka fail style.css dalam editor teks anda. Kami akan mentakrifkan pembolehubah CSS untuk warna gelap dan terang menggunakan pemilih :root. Ini membolehkan penyesuaian tema yang mudah di kemudian hari. Jika anda ingin menukar warna gelap atau terang, anda hanya perlu mengemas kininya di satu tempat.

/* 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. Sediakan gaya CSS asas. Tambahkan gaya untuk elemen badan, .container dan h1 untuk menetapkan reka letak dan tipografi halaman anda. Anda boleh menyesuaikan elemen ini mengikut cara yang anda suka.

  • body Pusatkan kandungan secara menegak dan mendatar menggunakan pembolehubah CSS untuk warna dan peralihan untuk perubahan warna yang licin.
  • .bekas Pusatkan kandungan dalam bekas kami.
  • h1 Tambahkan sedikit ruang di bawah tajuk.
/* 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. Tambahkan penggayaan CSS untuk mod gelap. Cipta kelas CSS bernama .mod-gelap yang menukar latar belakang dan warna teks apabila digunakan pada elemen.

/* Styles for dark mode */
.dark-mode {
    background-color: var(--clr-dark);
    color: var(--clr-light);
}

6. Gayakan ikon togol. Tambahkan gaya pada ikon SVG matahari dan bulan dan kawal keterlihatannya berdasarkan mod semasa.

/* 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;
}

Dengan gaya CSS ini, halaman anda akan mempunyai tema cahaya lalai. Kursor: sifat penunjuk menjelaskan bahawa togol boleh diklik.

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

Melaksanakan Kefungsian JavaScript

Sekarang kami mempunyai struktur HTML dan penggayaan CSS kami, sudah tiba masanya untuk menambah interaktiviti pada togol mod gelap kami dengan JavaScript dan melaksanakan storan setempat untuk mengingati keutamaan pengguna.

7. Pilih elemen DOM. Buka fail script.js dan pilih elemen DOM yang ingin kami ubah suai, ID themeTogol, yang mengandungi butang togol kami.

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.

Atas ialah kandungan terperinci Cara Membuat Togol Mod Gelap dengan HTML, CSS dan JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn