简体   繁体   English

重新加载页面后保持菜单切换状态

[英]Keep menu toggle state after page reload

Here's a toggle menu who works perfectly: If I click on the link (HTML code below), the menu folds. 这是一个非常有效的切换菜单:如果单击链接(下面的HTML代码),则菜单会折叠。 But I want if the users reload the page to keep the state of menu (expand / collapse). 但是我想要用户是否重新加载页面以保持菜单状态(展开/折叠)。

  $('#menu_toggle').click(function () { if ($('body').hasClass('nav-md')) { $('body').removeClass('nav-md'); $('body').addClass('nav-sm'); $('.left_col').removeClass('scroll-view'); $('.left_col').removeAttr('style'); $('.sidebar-footer').hide(); if ($('#sidebar-menu li').hasClass('active')) { $('#sidebar-menu li.active').addClass('active-sm'); $('#sidebar-menu li.active').removeClass('active'); } } else { $('body').removeClass('nav-sm'); $('body').addClass('nav-md'); $('.sidebar-footer').show(); if ($('#sidebar-menu li').hasClass('active-sm')) { $('#sidebar-menu li.active-sm').addClass('active'); $('#sidebar-menu li.active-sm').removeClass('active-sm'); } } }); 

 <a id="menu_toggle"><i class="fa fa-bars"></i></a> 

How to remember the state? 如何记住状态? Full project: http://demo.kimlabs.com/gentelella/production/index.html Thanks 完整项目: http : //demo.kimlabs.com/gentelella/production/index.html谢谢

You should use cookies to store booleans, of if the menu has been opened or closed. 您应该使用cookie来存储布尔值,例如菜单是否已打开或关闭。 Then when a page is loaded, it checks for any stored cookies, and by default uses those variables. 然后,在加载页面时,它将检查是否存储了任何cookie,并且默认情况下使用这些变量。

For example: 例如:

on page load: 页面加载:

var menuOutBoolean = Cookies.get("menuOutB") || false;
if (menuOutBoolean == true || menuOutBoolean == "true"){
    //put the menu out
}
else {
    //put menu in
}

On change: 更改时:

if (/*out*/){
    Cookies.set("menuOutB","true");
}
else{
    Cookies.set("menuOutB","false");
}

Note: Here I have used this JavaScript API (Jquery Plugin) . 注意:在这里,我使用了此JavaScript API(jQuery插件)

This is the sort of thing I'd use localStorage for. 这就是我要使用localStorage的那种东西。 Just set some kind of flag in localStorage when the state changes and fetch it when your page loads. 只需在状态更改时在localStorage中设置某种标志,并在页面加载时获取它即可。

I should add that using css classes to represent view state isn't a good idea and will bite you if your UI gets much more complicated. 我应该补充一点,使用css类表示视图状态不是一个好主意,如果您的UI变得更加复杂,它会咬您。

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

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