我有这个样本:
代码HTML:
<div class="square">
</div>
CODE CSS:
.square{
width:20px;
height:20px;
background:green;
}
.fa-square{
background:red;
width:20px;
height:20px;
}
CODE JS:
$("div").click(function(){
if ( $( this ).hasClass( "fa-square" ) ) {
$( this ).removeClass('fa-square').addClass('square');
}else{
$('.square').removeClass('square').addClass('fa-square');
}
});
我想做的只是相信...... 我想刷新页面按钮后保存状态
例如......如果按钮为绿色且为...则刷新后保持绿色刷新 如果按钮为红色,刷新后仍保留红色。
你怎么能这样做? 任何人都可以给我一个简单的例子吗?
提前致谢!
答案 0 :(得分:0)
您可以设置Cookie并在内容的开头读取它们,以检查状态是否设置为fiddle
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{} ()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
if(readCookie('state') == "fa-square"){
$('div').addClass('fa-square');
}else if(readCookie('state') == "square"){
$('div').addClass('square');
}
$("div").click(function () {
if ($(this).hasClass("fa-square")) {
$(this).removeClass('fa-square').addClass('square');
document.cookie= "state=square";
} else {
$('.square').removeClass('square').addClass('fa-square');
document.cookie= "state=fa-square";
}
});
答案 1 :(得分:0)
var retrievedObject = localStorage.getItem('class');
if(retrievedObject){
$('div').addClass(retrievedObject)
}
console.log('class ', (retrievedObject));
$("div").click(function () {
if ($(this).hasClass("fa-square")) {
$(this).removeClass('fa-square').addClass('square');
localStorage.setItem('class', 'square');
} else {
$('.square').removeClass('square').addClass('fa-square');
localStorage.setItem('class', 'fa-square');
}
});
这个利用localstorage来存储类的值然后在onload上将存储的类提供给div
答案 2 :(得分:0)
使用localStorage
$(function() {
var cls = 'state'; //key name for local storage
var sqr = $('.square');
sqr.addClass(localStorage.getItem(cls)); //restore state on page load
sqr.on('click', function() {
sqr.toggleClass('fa-square'); //shorthand for add/remove class
localStorage.setItem(cls, this.className); //preserve current state on every click
});
});
.square {
width: 20px;
height: 20px;
background: green;
}
.fa-square {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="square"></div>