简体   繁体   English

如何保持侧面菜单的切换状态

[英]How to keep toggle state of side menu

I need to edit this javascript that controls the slider menu, to keep slider menu current toggle position after page refresh 我需要编辑控制滑块菜单的此javascript,以在页面刷新后保持滑块菜单的当前切换位置

I've searched 2 dozen solutions on the webs without result 我在网上搜索了2打解决方案,但没有结果

I expect the menu to stay open or closed based on current toggle after page refresh but I can't figure out how to add the correct code to the script 我希望菜单根据页面刷新后的当前切换保持打开或关闭状态,但我不知道如何向脚本中添加正确的代码

    <script>
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
    document.body.style.backgroundColor = "rgb(0,0,0)";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
    document.body.style.backgroundColor = "black";
}
</script>

Based on Cuong le Ngoc's comment, you can do something like this. 根据Cuong le Ngoc的评论,您可以执行以下操作。 This code should be run when the page is loaded: 加载页面时应运行以下代码:

 var key = "menuState";

    try
    {
        /*Determine if the menu was closed, or if element does not exist in localstorage*/
        var menuOpen = localStorage.getItem(key);
        if (menuOpen === null || menuOpen === 'FALSE')
        {
            closeNav();                  //Close the menu.     
        }
        else
        {
             openNav();                  //Otherwise, the menu was open. Open it.
        }

    }
    catch (ex)
    {
        console.log("Unable to access local storage to update menu state. " +ex.message);
    }

Now in your openNav() and closeNav() , you can see the local storage value for the menu status element. 现在,在openNav()closeNav() ,您可以看到菜单状态元素的本地存储值。

   function openNav() {
   document.getElementById("mySidenav").style.width = "250px";
   document.body.style.backgroundColor = "rgb(0,0,0)";

   localStorage.setItem(key, 'TRUE');        //Mark menu as open.
   }

  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.body.style.backgroundColor = "black";

    localStorage.setItem(key, 'FALSE');    //Mark menu as closed.
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM