简体   繁体   中英

Can I affect CSS with JavaScript?

I'm new to all this so sorry if it's a stupid question. Basically, I have my CSS colours set up as three:root functions and the JavaScript has everything done for a light mode/dark mode toggle but now I want it so that when dark mode is true the colours in CSS change. Is there a way of doing this? (Even if it means duplicating the CSS and making the second one have the dark mode colours with JS choosing which file to choose based on the true or false statement of the toggle in HTML?

HTML/JS:

<li>
    <label>Night mode</label>
    <br>        
    <input type="checkbox" name="Nightmode" class="switch" id="nightModeCheckBox">
    <script>
        var nmbc = document.getElementById("nightModeCheckBox").checked;
        if (localStorage.getItem("nightMode") == "true"){
            document.getElementById("nightModeCheckBox").checked = true;
        }
    </script>
</li>
<li>
    <button onclick="settingsSave()" class="save">Save</button>
    <p id="saveText"></p>
    <script>
        function settingsSave() {
        var nmbc = document.getElementById("nightModeCheckBox").checked;
        if (typeof(Storage) !== "undefined") {
        localStorage.setItem("nightMode", nmbc);
        alert(localStorage.getItem("nightMode"));
        } else {
        alert("It seems your browser doesn't support local storage. Try updating it or using a different browser.");
        }
        }
        console.log(nmbc)
    </script>
</li>

CSS:

:root{
    --color1: White;
}

:root{
    --color2: rgb(230, 230, 230);
}

:root{
    --colorText: black;
}

document.documentElement.style.setProperty will do what you want

 document.documentElement.style.setProperty('--colorText', 'black'); document.documentElement.style.setProperty('--colorBack', 'yellow');
 :root { --colorText:Red; --colorBack:White; } body { color: var(--colorText); background-color: var(--colorBack); }
 <div> Should be BLACK on YELLOW not RED on WHITE </div>

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