简体   繁体   中英

Add button to switch between light and dark mode using two prefers-color-scheme

I have created a page with complex design and different background colors and I decided to add a button to let users switch between light and dark mode

I've tried different solutions with JS, but with no success. The current workaround I use is adding two media in my CSS file. Basically, if my website appearance is set to Dark, the page will also load dark-styled theme, and Light for Browser Light Appearance.

@media screen and (prefers-color-scheme: dark)
@media screen and (prefers-color-scheme: light)

Question is: How can I let users manually change between dark-light color-schemes manually with a button using vanilla Javascript? (not with the checkbox) Ps Maybe I could somehow implement this with var(--rule) in CSS but I'm still new to this stuff and I have almost zero JS knowledge

For example:

@media screen and (prefers-color-scheme: dark) {
    p, h2 {
        color: #e7e7e7;
    }
@media screen and (prefers-color-scheme: light) {
    p, h2 {
        color: #333333;
    }

html button (i class/button is a placeholder)

<div class="dark-mode-container">
  <div id="dark-mode-btn">
  <button class="theme-switch">test</button>
  <i class="fa-solid fa-moon" title="Switch to Dark mode"></i>
</div>

Here is my button inside sticky nav which I plan to use to switch modes导航栏内的暗模式按钮

I'd say use javascript, create a button and a javascript function onclick.

document.body.classList.toggle("dark-mode");

This function toggles the class dark-mode on the body, so for the darkmode style add body.dark-mode infront of all CSS selectors.

 const btn = document.getElementById('btn'); btn.addEventListener('click', function () { var elmWitchChange = document.getElementsByClassName('light') for (var i = 0; i < elmWitchChange.length; i++) { elmWitchChange[i].classList.toggle('dark') } })
 .dark { background-color: black; color: white; }
 <header class="light"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita, dolor? </header> <br> <div class="light"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus facilis qui magnam quidem facere autem maiores necessitatibus, hic maxime eum. </div> <br> <span class="light">Lorem ipsum dolor sit amet consectetur adipisicing elit. Eligendi, recusandae?</span> <br> <div> this div does not have a light class therefore it won't be effected </div> <br> <button class="light" id="btn">toggle</button>
in my opinion: if you want to make multiple elements react to your actions you can make a common class and use it so you can change their style

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM