我创建了一个切换输入,工作人员可以设置它们是否在办公室。我正在使用本地存储来保存输入的状态。当我在页面上添加多个切换输入时,每个输入的状态都可以改变,但是当我重新加载页面时,由于上次输入设置的本地存储(即全部输出),所有输入都是相同的。根据本地存储改变元素样式
如何保存每个切换状态并使用本地存储来记住这一点?
CSS代码
<style type="text/css">
.toggle {
-webkit-appearance: none;
appearance: none;
width: 150px;
height: 60px;
display: inline-block;
position: relative;
border-radius: 50px;
overflow: hidden;
outline: none;
border: none;
cursor: pointer;
background-color: red;
transition: background-color ease 0.3s;
}
.toggle:before {
content: "in out";
display: block;
position: absolute;
z-index: 2;
width: 80px;
height: 70px;
top: -5px;
left: -10px;
background: #fff;
border-radius: 50%;
font: 30px/70px Helvetica;
text-transform: uppercase;
font-weight: bold;
text-indent: -40px;
word-spacing: 85px;
color: #fff;
text-shadow: -1px -1px rgba(0,0,0,0.15);
white-space: nowrap;
box-shadow: 0 1px 2px rgba(0,0,0,0.2);
transition: all cubic-bezier(0.3, 1.5, 0.7, 1) 0.3s;
}
.toggle:checked {
background-color: #4CD964;
}
.toggle:checked:before {
left: 75px;
}
.toggle.in {
background-color: #4CD964;
}
.toggle.in:before {
left: 75px;
}
</style>
HTML代码
<input class="toggle" type="checkbox" />
<input class="toggle" type="checkbox" />
jQuery代码
var toggle = $('.toggle');
toggle.on('click', function(){
if ($('input[type=checkbox]:checked').length === 0) {
localStorage.setItem('result', 'out');
$(this).removeClass('in');
} else {
localStorage.setItem('result', 'in');
$(this).addClass('in');
}
})
if (localStorage.result === 'in') {
toggle.addClass('in');
} else {
toggle.removeClass('in');
}
你总是overwriteing同一个地方在你的localStorage('result')。您需要单独保存或作为字符串化对象/数组。 – Zammy
为获得最佳效果,请为每个输入使用“ID”,并为对象中的每个输入传递localStorage值。 –