簡體   English   中英

HTML5 本地存儲保存 .toggleClass

[英]HTML5 local storage save .toggleClass

如何將切換的類保存到 HTML 5 本地存儲中?

這是我的簡單切換功能:

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

我不太明白如何使用本地存儲,我遇到的所有示例都使用 .hide 和 .show 並且找不到與 toggleClass 相關的任何內容

我不想使用 .show 和 .hide 因為它們對瀏覽器來說很昂貴,但只需利用我的切換類......

小提琴:小提琴示例

代碼筆: http ://codepen.io/anon/pen/oLvNgB

  • 為元素使用 id,否則在切換(刪除)它的類后將無法定位該元素

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

  • 使用 !important 覆蓋背景顏色

#container {
   background-color: #ededed;
    height: 200px;
    width: 200px;
}

.with_toggle {
   background-color: #aeaeae !important;
}

  • 存儲切換的類名/狀態

//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


你可以使用方法“ $(element).hasClass(string class)

示例:

$('.bar-toggle').on('click',function(){
    if ($('.container').hasClass('.with_toggle')) {
       // mark as false 'cos in the next step u remove class .with_toggle
       localStorage.setItem("container_with_toggle", 0);
    } else {
       // mark as true 'cos in the next step u add class .with_toggle
       localStorage.setItem("container_with_toggle", 1);
    }
    $('.container').toggleClass('with_toggle');
});

當您訪問 localStorage 時:

var container_with_toggle = localStorage.getItem('container_with_toggle'); // return string zero or one ("0" or "1")
//So, u can use ternary
container_with_toggle = (container_with_toggle === "1") ? true : false;

而且,如果你設置像 boolean localStorage.setItem("container_with_toggle", true)這樣的值,你可以使用三元運算符或JSON.parse

var container_with_toggle = localStorage.getItem('container_with_toggle'); // return string with boolean notation ("false" or "true")
//Ternary
container_with_toggle = (container_with_toggle === "true") ? true : false;
// Or use JSON.parse
container_with_toggle = JSON.parse(container_with_toggle ); // return boolean true or false

請記住,在某些瀏覽器中,您需要使用window.localStorage

再見!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM