gpt4 book ai didi

javascript - localStorage 保存导航栏状态

转载 作者:行者123 更新时间:2023-11-30 19:01:08 24 4
gpt4 key购买 nike

我想使用 localStorage 来存储侧边栏切换,以便浏览器可以记住最后一个切换。有人可以看看这段代码并告诉我为什么它不起作用吗?

$(document).ready(function() {
var sidebarshow = localStorage.getItem('sidebar') == 'true';
$('#sidebar').toggleClass('active', sidebar);

$("#toggle").click(function() {
$("#sidebar").toggleClass("slow",function() {
localStorage.setItem('sidebarshow', 'active');
});
$("#sidebar").toggleClass("active");
});
});

CSS

#sidebar.active {
position: fixed;
top: 0;
left: 0;
background: #1F6482;
width: 250px;
height: 100%;
color: #FFF;
}
#sidebar {
position: fixed;
top: 0;
left: 0;
background: #1F6482;
width: 75px;
height: 100%;
color: #FFF;
}

最佳答案

问题:1)您没有为键'sidebar'设置localStorage,但是访问会导致意外的值。

var sidebarshow = localStorage.getItem('sidebar') == 'true';

问题:2) 你正在为键 'sidebarshow' 设置 localStorage,但是你没有在任何地方使用。 (至少在上面的代码中)

localStorage.setItem('sidebarshow', 'active');

将 localStorage 视为一个对象,其键和值的类型为字符串。确保先设置值,然后再获取它们。

这里是示例代码。

$(document).ready(function() {

/*
if (window && window.localStorage.getItem('sidebar') === 'active') {
// if it active show it as active
$("#sidebar").addClass("active");
} else {
$("#sidebar").removeClass("active");
} */

$("#toggle").click(function() {
$("#sidebar").toggleClass("active");
var updated = '';
if (window.localStorage.getItem('sidebar') === 'active') {
updated = 'not_active';
} else {
updated = 'active';
}
window.localStorage.setItem('sidebar', updated);
});
});
#sidebar.active {
position: fixed;
top: 0;
left: 0;
background: #1F6482;
width: 250px;
height: 100%;
color: #FFF;
}
#sidebar {
position: fixed;
top: 0;
left: 0;
background: #1F6482;
width: 75px;
height: 100%;
color: #FFF;
}

#toggle {
margin-left: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sidebar"> Sidebar here </div>

<button id="toggle"> toggle </button>

请检查 chrome 调试控制台示例的屏幕截图,稍作更改以进行测试。

enter image description here

关于javascript - localStorage 保存导航栏状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59504096/

24 4 0