HTML5本地存储保存.toggleClass [英] HTML5 local storage save .toggleClass
问题描述
如何将切换的类保存到HTML 5本地存储?
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');
});
我真的不明白如何使用本地存储以及我遇到的所有示例都使用了.hide和.show并且找不到与toggleClass相关的任何内容
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
我不想使用.show和.hide,因为它们对于浏览器来说代价很高但是只需要我的切换课程的优势......
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...
小提琴:
小提琴示例
codepen:
http://codepen.io/anon/pen/oLvNgB
推荐答案
- 对元素使用id,否则在切换(删除)它的类后将无法定位该元素
<a href="javascript:void(0)" class="bar-toggle">toggle and save state</a>
<div id="container">
</div>
- use!important覆盖背景颜色
#container {
background-color: #ededed;
height: 200px;
width: 200px;
}
.with_toggle {
background-color: #aeaeae !important;
}
- 存储类名/状态为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
这篇关于HTML5本地存储保存.toggleClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!