Keep CSS from refreshing on page reload

后端 未结 2 1231
梦毁少年i
梦毁少年i 2021-01-23 11:30

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.

2条回答
  •  旧时难觅i
    2021-01-23 12:19

    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';
    

提交回复
热议问题