Cara Menukar Laman Web Anda kepada Mod Gelap Menggunakan CSS dan JavaScript

PHPz
Lepaskan: 2024-08-23 14:32:32
asal
980 orang telah melayarinya

How to Switch Your Website to Dark Mode Using CSS and JavaScript

pengenalan

Mod gelap ialah tetapan paparan yang menggunakan latar belakang gelap dengan teks dan elemen terang. Ia telah mendapat populariti kerana ia kelihatan baik dan menawarkan beberapa faedah praktikal.

Faedah mod gelap termasuk:

  1. Tekanan Mata yang Dikurangkan: Mod gelap boleh menjadi lebih mudah pada mata, terutamanya dalam persekitaran cahaya malap, kerana ia mengurangkan jumlah cahaya terang yang dipancarkan daripada skrin.
  2. Hayat Bateri yang Dipertingkatkan pada Skrin OLED: Pada skrin OLED (Organic Light Emitting Diod), mod gelap boleh menjimatkan hayat bateri kerana piksel hitam pada asasnya dimatikan, menggunakan kurang kuasa berbanding dengan memaparkan warna-warna terang.

Dalam tutorial ini, kami akan membincangkan cara menukar tapak web anda kepada mod gelap menggunakan CSS dan JavaScript. Kami akan bermula dengan templat halaman web bertema ringan yang ringkas dan mengubahnya menjadi tapak web dengan mod terang/gelap boleh togol, membolehkan pengguna bertukar antara tema terang dan gelap dengan lancar.

Menyediakan Projek

Mari kita mulakan dengan templat halaman web bertema ringan yang ringkas. Kemudian, kami akan mengubahnya menjadi tapak web dengan mod terang/gelap boleh togol, membolehkan pengguna bertukar antara tema terang dan gelap.

Melaksanakan Gaya Mod Gelap

Memilih Warna

Langkah pertama ialah menyenaraikan semua warna yang kami gunakan dan pilih versi tema gelap untuk setiap satu. Dalam jadual di bawah, saya telah menyenaraikan semua warna pada halaman dan versi gelapnya yang sepadan.

Name Light version Dark version
body-bg #f4f4f4 #121212
primary-text #333333 #e0e0e0
header-footer-bg #333333 #181818
header-footer-text #ffffff #ffffff
section-bg #ffffff #1f1f1f
secondary-text #006baf #1e90ff
shadow rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.2)

Custom Variables

We then use CSS variables to create a dark and light class on body with those variables.

body.dark {
    --body-bg: #121212;
    --primary-text: #e0e0e0;
    --header-footer-bg: #1f1f1f;
    --header-footer-text: #ffffff;
    --section-bg: #1f1f1f;
    --secondary-text: #1e90ff;
    --shadow: rgba(0, 0, 0, 0.2);
}

body.light {
    --body-bg: #f4f4f4;
    --primary-text: #333333;
    --header-footer-bg: #333333;
    --header-footer-text: #ffffff;
    --section-bg: #ffffff;
    --secondary-text: #006baf;
    --shadow: rgba(0, 0, 0, 0.1);
}
Salin selepas log masuk

You can read about CSS variables in Using CSS custom properties. Essentially, they are entities defined using two dashes (--) that store values for reuse in a document. CSS variables make maintenance easier by allowing changes to update automatically.

Dynamic Element Colors

We use the var() CSS function to insert the values of the CSS variables. This way, we can dynamically change the color and update one variable to reflect changes across the entire document, instead of changing each one manually.

Here is an example of the nav element and its children:

body {
  background-color: var(--body-bg);
  color: var(--primary-text);
}

header, footer {
  background-color: var(--header-footer-bg);
  color: var(--header-footer-text);
}

article {
  background-color: var(--section-bg);
  box-shadow: 0 4px 8px var(--shadow);
}

a {
  color: var(--secondary-text);
}
Salin selepas log masuk

Toggle Light/Dark Mode with JavaScript

Now we can change the class of the body to dark or light to switch the theme. First, add a button to the header and set the changeTheme() function for its click event:

<button onclick="changeTheme()" class="theme-toggle">
    <svg> <!-- icon --> </svg>
</button>
Salin selepas log masuk

Define the changeTheme() function that toggles the class of the body:

function changeTheme() {
    if (document.body.classList.contains('light')) {
        document.body.classList.remove('light');
        document.body.classList.add('dark');
    } else {
        document.body.classList.remove('dark');
        document.body.classList.add('light');
    }
}
Salin selepas log masuk

And now users can change the theme of the website by clicking on the button.

You can see the code of the tutorial in the CodePen below

Next Steps

Additionally, you could store the user's theme preference in local storage. Updating the changeTheme() function to save the selected theme and check for it when the page loads will ensure the user's choice is remembered and applied automatically on their next visit.

function changeTheme() {
    if (document.body.classList.contains('light')) {
        document.body.classList.remove('light');
        document.body.classList.add('dark');
    } else {
        document.body.classList.remove('dark');
        document.body.classList.add('light');
    }

    // Save the current theme in localStorage
    const theme = document.body.classList.contains('dark') ? 'dark' : 'light';
    localStorage.setItem('theme', theme);
}

document.addEventListener('DOMContentLoaded', function () {
    // Get the saved theme from localStorage when the page loads
    const savedTheme = localStorage.getItem('theme') || 'light';
    document.body.classList.add(savedTheme);
});
Salin selepas log masuk

Adding the color-scheme: dark; property when in the dark theme can also ensure that some elements, which are otherwise hard to style, will have their styles changed by the browser.

body.dark {
  color-scheme: dark;
}
Salin selepas log masuk

Conclusion

In conclusion, adding dark mode to your website can improve user experience by reducing eye strain and extending battery life on OLED screens. By following this guide, you can easily set up a light/dark mode toggle using CSS and JavaScript. Customize the dark mode to fit your design.

Share your implementations or ask questions in the comments below.

Atas ialah kandungan terperinci Cara Menukar Laman Web Anda kepada Mod Gelap Menggunakan CSS dan JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
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
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!