如何本地存储展开/折叠CSS设置

时间:2012-10-11 08:50:06

标签: javascript css html5 local-storage web-storage

我正在寻找使用本地存储来记住展开/折叠元素的CSS设置的方法

所以我的JavaScript看起来像这样(抓取id并处理展开/折叠)

function toggleHeight(id, link) {
    var e = document.getElementById(id);

    if(e.style.maxHeight == '450px') {
        e.style.maxHeight = '0px'; 
    } else {
        e.style.maxHeight = '450px';
    }
}

所以我正在寻找的东西可以抓住div id点击链接并在点击时存储更改,然后在刷新时记住。

3 个答案:

答案 0 :(得分:1)

也许是这样的

var height = localStorage.getItem(id+"-height");

localStorage.setItem(id+"-height", height);

答案 1 :(得分:1)

这里承诺的是我的解决方案:

<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>

这会在点击时存储div的状态并设置为打开/关闭

在页面加载时,它会抓取存储的值并在打开/关闭值后设置最大高度css ..

希望其他人可以利用这个

答案 2 :(得分:0)

这就是我解决它的方式:工作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');​

您看到我将节目分开并隐藏,因此您也可以单独隐藏它们,如果您愿意或仍然可以使用切换方法。