保存选择菜单隐藏/显示

时间:2018-05-17 18:33:42

标签: javascript menu save

我想让我的用户选择是否总是想要显示或隐藏带有某种复选框的侧边菜单。

所以我的代码是显示和隐藏的基本功能。但是我怎么能保存这个呢?我应该在哪里保存缓存中的选择(设置)?

请有人帮帮我吗?

function openNavLeft() {
    document.getElementById("SideNavLeft").style.width = "250px";
}

function closeNavLeft() {
    document.getElementById("SideNavLeft").style.width = "0";
}
<ul class="nav navbar-nav">
    <li><a onclick="openNavLeft()">Menu</a></li>
</ul>



<!--- Left Sidenav Content -->
<div id="SideNavLeft" class="sidenav sidenav_left">
    <div class="top-block-side-nav">
        <a href="javascript:void(0)" class="closebtn" onclick="closeNavLeft()">&times;</a>
    </div>


    <a href="#">>
        <div class="menu_element">
            <div class="nav_icon" id="x"></div>
            <p class="menu_title">My Employee</p>
        </div>
    </a>

    <a href="#">
        <div class="menu_element">
            <div class="nav_icon" id="icon_vacation"></div>
            <p class="menu_title">Vacation</p>
        </div>
    </a>

    <a href="#">>
        <div class="menu_element">
            <div class="nav_icon" id="x"></div>

            <p class="menu_title">Mis Envios</p>
        </div>
    </a>
    <a href="#">">
        <div class="menu_element">
            <div class="nav_icon" id="x"></div>
            <p class="menu_title"> Setting</p>
        </div>
    </a>
</div>
<!--- EndLeft Sidenav Content -->

1 个答案:

答案 0 :(得分:0)

您可以将其保存在像这样的cookie中

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
if(!getCookie('SideNavLeft'))
    setCookie('SideNavLeft', '250', 100) // sets cookie for 100 days to initial value of 250 ie vissible menu as most obvious default

function openNavLeft() {
    setCookie('SideNavLeft', '250', 100)
}

function closeNavLeft() {
    setCookie('SideNavLeft', '0', 100);
}
// then wherever in code you can set the style of menu like so:
document.getElementById("SideNavLeft").style.width = getCookie('SideNavLeft')+"px";

或@kurt在对localStorage或sessionStorage的评论中提及。 您可以在此处阅读有关差异的内容,例如https://scotch.io/@PratyushB/local-storage-vs-session-storage-vs-cookie