2014-06-12 50 views
0

我爲我的網站創建了一個面板div,當我們點擊按鈕時滑出頁面,當我們再次點擊時再次出現。在localStorage中保存菜單位置

HTML很簡單,只有面板顯示/隱藏它的按鈕。

<div id="panel"> 
    <div id="close"></div> 
</div> 

而且我腳本但存儲不起作用:

function storePanel(right){ 
    var panelData = localStorage.getItem('panel'); 
    if (panelData!=undefined) 
     panelData=JSON.parse(panelData); 
    else 
     panelData={"right":"24px"};// a starting value 
    panelData["top"]=top; 
    panelData["right"]=right; 
    localStorage.setItem('panel', JSON.stringify(panelData)); 
} 



// hide/show panel 

document.getElementById('close').onclick = function() { 
    var panel = document.getElementById("panel"); 
    var right = panel.style.right; 
    var icon = document.getElementById("icone"); 
    if (right == "24px") { 
     right = "-200px"; 
    } 
    else { 
     right = "24px"; 
    } 
    panel.style.right = right; 
    storePanel(right); 
}; 

這裏是jsfiddle

+0

等待,爲什麼你需要保存呢?你所做的一切是否將它從視圖中移出? – Bioto

+0

@NicholasYoung我需要保存他的位置,如果我們關閉菜單,在重新加載菜單上關閉。 – remibenault

+0

你可以使用一個cookie。 – Adjit

回答

0

您的storePanel功能不正確。首先,如果面板是否正確,您爲什麼只用一個對象來存儲對象?即使你最終會改變它,使面板可以在多個地方,你只需要一個數字 - 你爲什麼要存儲panelData? (這只是一個簡化)。另外,您可以正確存儲該值,但不會在頁面加載時檢索它以更改面板。你完成的代碼看起來應該像這樣(簡化):

// Note: I used a variable to keep track of whether the div was to the right or not 
var isRight = true; 

function storePanel(right) { 
    // Simple 
    localStorage.setItem('panel.right', right); 
} 

function updatePanel() { 
    var panel = document.getElementById("panel"); 
    var right; 
    if (isRight) { 
     right = "-200px"; 
    } 
    else { 
     right = "24px"; 
    } 
    panel.style.right = right; 
    isRight = !isRight; 
    storePanel(isRight); 
} 

// When the page loads, show or hide panel 

isRight = localStorage.getItem("panel.right") == "false"; 

updatePanel(); 


// hide/show panel 

document.getElementById('close').onclick = function() { 
    // var icon = document.getElementById("icone"); 
    updatePanel(); 
}; 

http://jsfiddle.net/prankol57/YtM7y/

+0

非常感謝您,事實是,我使用腳本將div的位置保存到localStorage中,並嘗試將其編輯爲我的菜單。但我麻煩了解Javascript和Jquery :) – remibenault

0

你可能遇到了問題,導致盲目使用javascript速記,比如避免牙套在「if」聲明上。

function storePanel(right){ 
    var panelData = localStorage.getItem('panel'); 
    if (panelData) { 
     panelData=JSON.parse(panelData); 
    } else { 
     panelData={ 
      "right": right || "24px", //will assign 24px if right is not set. 
      "top": top 
     }; 
    } 
    localStorage.setItem('panel', panelData); 
} 

謹慎使用JSON.stringify,因爲它可能會對對象的引號進行雙重編碼,從而導致它無效。