如何将切换的类保存到HTML 5本地存储中?
这是我的简单切换功能:
/* Toggle */
$('.bar-toggle').on('click',function(){
$('.container').toggleClass('with_toggle');
});
我真的不明白如何使用本地存储,我遇到的所有示例都使用.hide和.show,但找不到与toggleClass相关的任何内容
我不想使用.show和.hide,因为它们对于浏览器来说代价很高,但只是利用了我的切换类......
小提琴: fiddle example
codepen: http://codepen.io/anon/pen/oLvNgB
答案 0 :(得分:2)
<a href="javascript:void(0)" class="bar-toggle">toggle and save state</a>
<div id="container">
</div>
#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
答案 1 :(得分:1)
你可以使用方法&#34; $(element).hasClass( string class )&#34;
示例:强>
$('.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;
并且,如果您将值设置为布尔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
。
再见!