我有一个已成功隐藏和显示的侧边栏菜单。当侧边栏菜单被隐藏并且我刷新页面或浏览器时,隐藏的侧边栏菜单将返回到其原始外观,而不是隐藏时的位置。问题是如何锁定以使侧边栏菜单显示保持在隐藏位置。我已经尝试使用 javascript 多次,但仍然失败。请帮忙谢谢。
.sidebar {
height: 100%;
width: 250px;
position: fixed;
left: 0;
top: 0;
z-index: 1000;
background-color: var(--sidebar-color);
color: #fff;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.5), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
transition: all 0.5s ease;
overflow-y: auto;
/* hide scrollbar for IE, Edge and Firefox */
-ms-overflow-style: none;
scrollbar-width: none;
}
.sidebar.expand {
width: 65px;
}
var btnToggle = document.querySelector("#btnToggle");
var sidebar = document.querySelector(".sidebar");
btnToggle.onclick = function() {
sidebar.classList.toggle("expand");
}
最佳答案
如果你想让它持久化,你需要使用localStorage
来存储侧边栏的状态。然后,当页面重新加载时,您可以从 localStorage
读取状态,并将该类相应地设置到侧边栏。
下面未经测试的代码:
var btnToggle = document.querySelector("#btnToggle");
var sidebar = document.querySelector(".sidebar");
// When the page loads, use localStorage to set the initial class
if(localStorage.getItem("expand") && localStorage.getItem("expand") == "true"){
sidebar.classList.add("expand");
}
btnToggle.onclick = function() {
sidebar.classList.toggle("expand");
localStorage.setItem("expand", sidebar.classList.contains("expand"));
}
我创建了一个minimal code pen来说明它是如何工作的。我还添加了您在评论中提到的滑入动画。
关于javascript - 如何锁定刷新页面时隐藏的侧边栏菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67820745/