简体   繁体   中英

How to prevent CSS from changing when another tab(link) is clicked and the user is remaining on the same page?

I have made a button and when it is clicked the colors of my website will change (which works fine). However, when a link is clicked or the page is refreshed it will not save the new css color values, it will just go back to how the page looks by default. Please let me know how I can save these values so it will not change on page refresh or when a tab is clicked. I appreciate any help you can give:)

Thank you!!

function toggleDarkLight(event) {
  var body = document.getElementById("body");
  var currentClass = body.className;
  body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
 }
<body id="body" class="light-mode">
<button type="button" name="dark_light" onclick="toggleDarkLight()" title="Toggle dark/light mode">dark</button></body>

You should use localStorage

document.body.onload=function(){
        var mode = localStorage.getItem("mode")=="" ? mode="light-mode" :  mode=localStorage.getItem('mode');
        var body = document.getElementById("body");
        body.className = mode;
    }

    function toggleDarkLight(event) {
        var body = document.getElementById("body");
        var currentClass = body.className;
        body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
        localStorage.setItem("mode",body.className)
    }

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