Store a css class on browser

后端 未结 1 1387
醉酒成梦
醉酒成梦 2021-01-27 03:22

My project has the option to change the site theme by clicking on a link:

  • Contact
1条回答
  •  清酒与你
    2021-01-27 03:54

    Localstorage will provide you a possibilty to store the data without expiration-date:

    $('.change-theme').click(function () {
        $('body').toggleClass('theme-dark');
        if($('body').hasClass('theme-dark')){
            localStorage.setItem('theme', 'theme-dark');
        }
    });
    
    $(document).ready(function(){
        var theme = localStorage.getItem('theme');  
        if(theme !== ''){      
            $('body').addClass(theme);
        }
    });
    

    Whereas sessionStorage will store the data only for one session, until the browser is closed (usage is the same as localStorage).

    All major Browser support this feature, the Internet Explorer support this since version 8.

    Note: you can only store strings in the Webstorage.

    If you want to use cookies instead you can try:

    document.cookie="theme=theme-dark"; //setter
    

    and

    var x = document.cookie; //getter
    

    Reference

    webStorage

    cookies

    0 讨论(0)
提交回复
热议问题