简体   繁体   中英

How to revert changes to css made by javascript

So I have a button that toggles a simple dark theme for my web app.

<button class="btn btn-primary" onclick="dark_mode()">Dark Mode ON</button>

Once the user clicks it will activate this function in javascript.

function dark_mode() {
    document.body.style.background = "#2C2F33";}

This will only change the background. I am wondering if the user clicks the button a second time it will revert the changes made by the function. (ie toggle on/off) Thanks for the time and help in advance!

Just check and change the style using a ternary operator:

function dark_mode() {
    document.body.style.background = document.body.style.background == "#2C2F33" ? "#FFFFFF" : "#2C2F33";
}

You can make it by toggling CSS class, it is more flexible solution

 function dark_mode() { document.body.classList.toggle('dark-mode') } 
 .dark-mode { background: #2C2F33 } 
 <button class="btn btn-primary" onclick="dark_mode()">Dark Mode ON</button> 

If the user clicks again, the function is simply called again. So, after the first click there are no more changes.

A better way would be to assign your dark mode styles to a class, say "btn--dark-mode" and then use js to toggle that class:

 function dark_mode() { document.querySelector('#dark-mode-toggle').classList.toggle('dark-mode'); // ie9+ only } 
 .btn--dark-mode { background-color: #2C2F33; } 
 <button id="dark-mode-toggle" class="btn btn-primary" onclick="dark_mode()">Dark Mode ON</button> 

This will apply the class or take it off depending on whether it is already there.

You can use data tags to track current theme :

<button class="btn btn-primary" onclick="dark_mode(this);" data-dark-theme="on" >Dark Mode ON</button>

JS :

function dark_mode(ctrl) {
var darkTheme = ctrl.getAttribute("data-dark-theme"); 
  if(darkTheme== "on"){
    ctrl.setAttribute("data-dark-theme", "off"); 
    document.body.style.background = "#2C2F33";
    ctrl.innerHTML  = "Dark Mode OFF";
  }
  else {
    ctrl.setAttribute("data-dark-theme", "on"); 
    document.body.style.background = "#FFFFFF";
    ctrl.innerHTML  = "Dark Mode ON";
  }
}

Working demo

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