[英]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
<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
你可以使用方法“ $(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.