简体   繁体   中英

How to overwrite CSS color scheme settings

In HTML. Now I know we can ask CSS to do something when user change their system color scheme, like

@media (prefers-color-scheme: dark)

But what if I want to overwrite that setting like I need light color scheme at night, but I don't want to change my system color scheme settings, is there any JavaScript or jQuery way to fool CSS (to proceed the dark park even when system is light, or opposite ), so I can switch webpage color scheme by click some element?

You can define two classes for it. Eg. "colourSchemeDay" and "colourSchemeNight" in your CSS file. Then, you can manipulate the classes by having a time constraint on them.

if (time >=6AM && time <= 8PM){
    document.getElementById("myElement");
    element.classList.remove("colourSchemeNight");
    element.classList.add ("colourSchemeDay");
} else {
    document.getElementById("myElement");
    element.classList.add("colourSchemeNight");
    element.classList.remove("colourSchemeDay");
}

You should first get the current time in 24 hour format like so:

var dayNight = (new Date()).getHours();

Now, you most probably have 2 classes with background color, 1 for day and 1 for night.

So, you can use if/else statement to decide when you want to add or remove a class using JQuery.

So in my example, when the .dayNight is bigger or equals to 7 (7am) and lesser than 19 (7pm), it adds the .day class and removes the. night class.

And when the .dayNight is bigger or equals to 0 (12 midnight) AND if it is smaller than 7 (7am), it adds the .night class and removes the .day class.

Also, when it is bigger or equals to 19 (7pm) and equals or lesser than 23 (11pm) it does the same above. We've already assigned 0 (12 midnight) in the above code, so we can set it to 23 (11pm) here.

Try this:

 var dayNight = (new Date()).getHours(); if(dayNight>=7 && dayNight < 19) { $( "#display" ).removeClass( "night" ).addClass( "day" ); } if((dayNight>=0 && dayNight<7) || (dayNight>=19 && dayNight <=23)) { $( "#display" ).removeClass( "day" ).addClass( "night" ); }
 .day { background-color: blue; color: white; }.night { background-color: red; color: white; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="display"> Hello! </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