这就是我解决它的方法:工作小提琴
//extra methods to get and set objects in staid of strings
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
//fetch the object or make a new and set constant values
var toggleState = localStorage.getObject('toggleState') || {},
MIN_SIZE= '0px',
MAX_SIZE= '450px';
//shown is an optional parameter
function toggleHeight(id, shown) {
var e = document.getElementById(id);
if(shown === true || (typeof shown === "undefined" && e.style.maxHeight == MIN_SIZE)) {
show(id);
} else {
hide(id);
}
}
function show(id){
var e = document.getElementById(id);
e.style.maxHeight = MAX_SIZE;
toggleState[id] = true;
localStorage.setObject('toggleState',toggleState);
}
function hide(id){
var e = document.getElementById(id);
e.style.maxHeight = MIN_SIZE;
toggleState[id] = false;
localStorage.setObject('toggleState',toggleState);
}
//loop over it to set initial values
for(var i in toggleState){
toggleHeight(i, toggleState[i]);
}
//do manual toggle, hide, show
toggleHeight('someID');
你看我把显示和隐藏分开了,所以你也可以单独显示隐藏它们,如果你愿意的话,或者你仍然可以使用切换方法。