在页面重新加载时保持CSS不刷新 [英] Keep CSS from refreshing on page reload
问题描述
我有一个带有两个CSS文件的html页面 - 一个用于灯光主题,另一个用于黑暗主题。单击相应按钮时,主题将更改为light.css或dark.css。
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.
然而,每当我刷新页面,重新加载页面,返回等等。它会变回默认的css(作为light.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).
当我点击按钮并刷新页面时,有什么方法可以让它保持在dark.css主题上?
Is there any way I can get it to stay on the dark.css theme when I click the button and refresh the page?
谢谢。
推荐答案
您可以使用cookie,localStorage或sessionStorage保存默认主题和选择的主题。因此,当您的页面加载时,您必须从cookie / localStorage / sessionStorage中读取该信息并应用所选主题。
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.
例如当页面加载时
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';
这篇关于在页面重新加载时保持CSS不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!