HTML5 local storage save .toggleClass

前端 未结 2 1356
孤独总比滥情好
孤独总比滥情好 2020-12-20 08:36

How Can I save the toggled class into HTML 5 local storage?

This is my simple toggle function:

 /* Toggle */
    $(\'.bar-toggle\').on(\'click\',func         


        
2条回答
  •  感情败类
    2020-12-20 09:22

    • use an id for the element, otherwise won't be able to target that element after toggling (removing) it's class

    toggle and save state
    

    • use !important to override the background-color

    #container {
       background-color: #ededed;
        height: 200px;
        width: 200px;
    }
    
    .with_toggle {
       background-color: #aeaeae !important;
    }
    

    • storing the class name/state of toggled

    //retrieve current state
    $('#container').toggleClass(window.localStorage.toggled);
    
    /* Toggle */
    $('.bar-toggle').on('click',function(){
    
       if (window.localStorage.toggled != "with_toggle" ) {
          $('#container').toggleClass("with_toggle", true );
          window.localStorage.toggled = "with_toggle";
       } else {
          $('#container').toggleClass("with_toggle", false );
          window.localStorage.toggled = "";
       }
    
    });
    

    http://jsbin.com/wimojapowo/1/edit?html,css,js,output


    https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API


提交回复
热议问题