2012-10-11 141 views
0

我正在尋找的方式來使用本地存儲記住展開/摺疊元素如何本地存儲擴展/摺疊CSS設置

所以我的JavaScript看起來像這樣(這抓住ID的CSS設置和處理展開/摺疊)

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

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

所以我要尋找的東西,抓住DIV IDPå點擊一個鏈接,點擊,然後記住,當存儲改變是,當耳目一新。

回答

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> 

點擊時,該存儲格的狀態,並設置在打開/關閉

在頁面加載它抓住的存儲值,並將最大打開/關閉值後-height CSS ..

希望有其他人可以利用這個

1

也許這樣的事情

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

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

是的,我與此找到感覺,而不是它是不是第掠的高度CSS設置e div並將其存儲爲值NULL – megaman

+0

用「e.style.maxHeight」替換設置的項目值「height」,如下所示:將高度存儲爲thx很多:) var height = localStorage.getItem(id +「 - height 「); localStorage.setItem(id +「 - height」,e.style.maxHeight); – megaman

+0

是的,你需要在寫入存儲之前設置高度:) - 隨時接受答案。 – Jeff

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');​ 

你看我分開顯示和隱藏,所以你可以單獨顯示隱藏他們也一樣,如果你想要還是可以使用切換方法。

+0

感謝您的回答讓我更接近,但結束了一些更簡單的事情 – megaman