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

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...