Keep CSS from refreshing on page reload

后端 未结 2 1300
梦毁少年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条回答
  •  没有蜡笔的小新
    2021-01-23 12:12

    If you don't want to use back-end methods to substitute the style.css file, you can try using local storage like this:

    If you don't want to use back-end methods to substitute the style.css file, you can try using local storage like this:

    $(function(){
    
      setSiteTheme(getSiteTheme());
      
      function setSiteTheme(themeName) {
        //Uncomment this in your app: window.localStorage.setItem('themeName', themeName);
        $('link[data-theme]').attr('href', themeName);
      }
      
      function getSiteTheme() {
        //Uncomment this in your app: return window.localStorage.getItem('themeName') || 'light.css';
      }
    });
    
    
    

    After that add DATA-THEME attribute to the link tag of the head. And don't forget to uncomment necessary lines.

提交回复
热议问题