使用jquery localStorage时,边栏导航会出现,然后在页面加载时消失

时间:2017-02-05 00:49:21

标签: javascript jquery css html5

我正在使用jQuery localStorage来记住侧边栏导航菜单的切换状态,使用以下内容 jQuery代码:

$('#wrapper').toggleClass(window.localStorage.toggled);
$('#menu-toggle').on('click',function(e)
{
    e.preventDefault();
    if (window.localStorage.toggled != "toggled" ) 
    {
        $('#wrapper').toggleClass("toggled", true );
        window.localStorage.toggled = "toggled";
    } 
    else 
    {
        $('#wrapper').toggleClass("toggled", false );
        window.localStorage.toggled = "";
    }
});

通过记住切换状态,代码可以正常工作。刷新页面时出现问题。侧边栏导航菜单首先出现然后消失。我已经尝试在css中设置display:none但它似乎不起作用。

相关的HTML代码:

<a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><span class="glyphicon glyphicon-th-list"></span></a>

<div id="wrapper">
</div>

1 个答案:

答案 0 :(得分:0)

以下是我如何实现目标。请注意,我使用了一个代码段来组织代码,但由于沙盒不允许访问本地存储,因此无法在SO上运行。但是你可以看到它的实际效果..

Working jsFiddle

/**
 * Feature detect + local reference for simple use of local storage
 * if (storage) {
 *    storage.setItem('key', 'value');
 *    storage.getItem('key');
 * }
 */
var storage;
var fail;
var uid;
try {
  uid = new Date;
  (storage = window.localStorage).setItem(uid, uid);
  fail = storage.getItem(uid) != uid;
  storage.removeItem(uid);
  fail && (storage = false);
} catch (exception) {}
/* end  Feature detect + local reference */

$(function() {

  if (storage) {
    $('#wrapper').toggleClass('isOpen', storage.getItem('isOpen') == '1');
    $('#menu-toggle').on('click', function(e) {
      e.preventDefault();
      var setOpen = storage.getItem('isOpen') == '1' ? 0 : 1; // set opento the oposite of current
      storage.setItem('isOpen', setOpen);
      $('#wrapper').toggleClass('isOpen', setOpen);
    });
  } 
  
});
#wrapper:not(.isOpen) {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><span class="glyphicon glyphicon-th-list"></span></a>

<div id="wrapper">
  some content here
</div>