How to local storage expand/collapse CSS settings
-
06-07-2021 - |
質問
I'm looking for way to use local storage to remember the CSS settings of a expand/collapse element
so for my JavaScript looks like this (which grabs the id and handles the expand/collapse)
function toggleHeight(id, link) {
var e = document.getElementById(id);
if(e.style.maxHeight == '450px') {
e.style.maxHeight = '0px';
} else {
e.style.maxHeight = '450px';
}
}
So what I am looking for is something that grabs the div id på clicking a link and stores the changes when clicking and then remembering is when refreshing.
解決 2
As promised here is my solution:
<script type="text/javascript">
function toggleHeight(id, link) {
var e = document.getElementById(id);
var height = localStorage.getItem(id);
if(e.style.maxHeight == '450px' || e.style.maxHeight == 'inherit') {
e.style.maxHeight = '0px';
localStorage.setItem(id,"closed");
} else {
e.style.maxHeight = '450px';
localStorage.setItem(id, "open");
}
}
function load() {
var setting
var e
var link
for (x in localStorage){
setting = localStorage.getItem(x);
e = document.getElementById(x);
link = document.getElementById('forumlink'+x);
if (setting == 'open')
{
e.style.maxHeight = '450px';
}
else
{
e.style.maxHeight = '0px';
}
}
}
</script>
This stores the state of the div when clicked and sets in to open/closed
On page load it grabs the stored value and sets the max-height css after the open/closed value..
Hope some others can make use of this
他のヒント
Maybe something like this
var height = localStorage.getItem(id+"-height");
localStorage.setItem(id+"-height", height);
This is how I solved it: working fiddle
//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');
You see I separated the show and hide so you can show hide them individually too, if you want or you can still use the toggle method.