Heim > Web-Frontend > js-Tutorial > So fügen Sie ganz einfach den Dunkelmodus zu Ihrer Website hinzu

So fügen Sie ganz einfach den Dunkelmodus zu Ihrer Website hinzu

WBOY
Freigeben: 2024-08-26 21:41:32
Original
381 Leute haben es durchsucht

How to Easily Add Dark Mode to Your Website

Hey! So, if you’re like me and love the whole dark mode vibe, you might have thought about adding it to your website. It’s pretty easy to set up with just a bit of CSS and JavaScript. Here’s how I did it.

Step 1: Setting Up the HTML

First off, you need a button or a switch that users can click to toggle between light and dark modes. I went with a simple button for this example(you can use an icon if you want):

<button id="dark-mode-toggle">Toggle Dark Mode</button>
Nach dem Login kopieren

This button is going to be the trigger for switching modes.

Step 2: Adding the CSS for Light and Dark Modes

Next, you need to define what your light mode and dark mode will look like. In your CSS, you’ll set up the default styles (which will be your light mode) and then add a dark mode class that overrides these styles.

body {
    background-color: white;
    color: black;
    transition: background-color 0.3s, color 0.3s;
}

.dark-mode {
    background-color: #121212;
    color: #ffffff;
}
Nach dem Login kopieren

Here’s what’s happening:

  • Light Mode (Default): The body has a white background and black text. I added a transition to make the change smooth when switching between modes.
  • Dark Mode: The .dark-mode class changes the background to a dark grey and the text to white.

Step 3: Switching Between Modes with JavaScript

Now comes the part where we make the button actually do something. This bit of JavaScript will toggle the .dark-mode class on the body whenever the button is clicked.

const toggleButton = document.getElementById('dark-mode-toggle');
const body = document.body;

toggleButton.addEventListener('click', () => {
    body.classList.toggle('dark-mode');

    // Save the user's preference in local storage
    if (body.classList.contains('dark-mode')) {
        localStorage.setItem('theme', 'dark');
    } else {
        localStorage.setItem('theme', 'light');
    }
});
Nach dem Login kopieren

Here’s a breakdown:

  • Toggle the Class: When the button is clicked, we toggle the .dark-mode class on the body. This changes the styles between light and dark modes.
  • Saving Preference: I added a little extra by saving the user’s preference in localStorage. This means if they choose dark mode, it’ll stay that way even if they leave and come back to the site.

Step 4: Loading the User’s Preference on Page Load

To make sure the site loads in the user’s preferred mode, you need to check localStorage when the page loads and set the mode accordingly.

window.addEventListener('load', () => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark') {
        body.classList.add('dark-mode');
    }
});
Nach dem Login kopieren

If you’re using React, the process is pretty similar, but you’ll handle things within your components. Here’s how to do it:

  1. Set Up State and CSS Class for Dark Mode:

Use React’s useState to manage the dark mode state, and apply the appropriate class to your root element:

   import React, { useState } from 'react';

   function App() {
       const [darkMode, setDarkMode] = useState(false);

       const toggleDarkMode = () => {
           setDarkMode(!darkMode);
       };

       return (
           <div className={darkMode ? 'dark-mode' : ''}>
               <button onClick={toggleDarkMode}>
                   {darkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'}
               </button>
           </div>
       );
   }

   export default App;
Nach dem Login kopieren

In this example:

  • The darkMode state determines if the dark mode is active.
  • The toggleDarkMode function toggles the dark mode on and off.
  1. CSS for Dark Mode:

Add the .dark-mode class to your CSS, just like before:

   body {
       background-color: white;
       color: black;
       transition: background-color 0.3s, color 0.3s;
   }

   .dark-mode {
       background-color: #121212;
       color: #ffffff;
   }
Nach dem Login kopieren
  1. Local Storage:

If you want the theme preference to persist, you can add this small tweak:

   import React, { useState, useEffect } from 'react';

   function App() {
       const [darkMode, setDarkMode] = useState(() => {
           const savedTheme = localStorage.getItem('theme');
           return savedTheme === 'dark';
       });

       useEffect(() => {
           localStorage.setItem('theme', darkMode ? 'dark' : 'light');
       }, [darkMode]);

       return (
           <div className={darkMode ? 'dark-mode' : ''}>
               <button onClick={() => setDarkMode(!darkMode)}>
                   {darkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'}
               </button>
           </div>
       );
   }

   export default App;
Nach dem Login kopieren

Here’s what’s happening:

  • Initial State: The initial state of darkMode is set based on the value stored in localStorage.
  • Effect Hook: The useEffect hook saves the current theme preference whenever darkMode changes.

And that’s it! This is a simpler way to add dark mode to your React app without overcomplicating things.

Das obige ist der detaillierte Inhalt vonSo fügen Sie ganz einfach den Dunkelmodus zu Ihrer Website hinzu. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage