Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

javascript - HTML5 local storage save .toggleClass

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

This is my simple toggle function:

 /* Toggle */
    $('.bar-toggle').on('click',function(){
      $('.container').toggleClass('with_toggle');
    });

I don't really understand how to use the local storage and all the examples I came across use the .hide and .show and cannot find anything related to toggleClass

I wouldn't want to use the .show and .hide as they are costly for the browser but just take advantage of my toggle class...

fiddle: fiddle example

codepen: http://codepen.io/anon/pen/oLvNgB

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

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

<a href="javascript:void(0)" class="bar-toggle">toggle and save state</a>
<div id="container">
</div>

  • 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



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...