Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

javascript - Keep CSS from refreshing on page reload

I have a html page with two CSS files - one for a light theme and one for a dark theme. When I click the respective button, the theme changes to either light.css or dark.css.

However, whenever I refresh the page, reload the page, go back etc. It changes back to the default css (being the light.css file).

Is there any way I can get it to stay on the dark.css theme when I click the button and refresh the page?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a cookie, localStorage or sessionStorage where you keep the default theme and the choosen one. So when your page loads you have to read that info from cookie/localStorage/sessionStorage and to apply the chosen theme.

e.g when page is loading

let theme = localStorage.getElement('theme');
if(!theme){
theme = 'light';
localStorage.setElement('theme', 'light');
}
// and you use theme variable to load the light theme

e.g when the user changes the theme

localStorage.setElement('theme', 'dark');
theme = 'dark';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...