Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

html - how do i make it switch to black or white like a dark mode and light mode?

hello so I'm in the process of making a website right now and need some help. you see, i made this very cool switch link to see the switch= (https://drive.google.com/file/d/1613Pz0WJbdzKdyQWRQ-JUE2Kj--yoDIK/view?usp=sharing) (may have to download it) and I would like to know how I can make it change the background of the website. so when you flip it it turns black flip it again it turns white. can anyone help?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use CSS variables and a little bit of JavaScript to switch themes.

Define the theming in the .light or the .dark then set the class of the body to it. It will set the variables to the theme color.

Ex:

function toLight() {
  document.body.classList.remove('dark');
  document.body.classList.add('light');
}

function toDark() {
  document.body.classList.remove('light');
  document.body.classList.add('dark');
}
.light {
  --font-color: #111;
  --bg-color: #fff;
}

.dark {
  --font-color: #eee;
  --bg-color: #111;
}

p, h1 {
  color: var(--font-color);
}

body {
  background-color: var(--bg-color);
}
<body class="light">
  <h1>title</h1>
  <p>text blah blah</p>
  
  <button onclick="toDark()">switch to dark</button>
  <button onclick="toLight()">switch to light</button>
</body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...