我需要编辑用于控制滑块菜单的JavaScript,以在页面刷新后保持滑块菜单当前的切换位置
我在网上搜索了2打解决方案,但没有结果
我希望菜单在刷新页面后根据当前切换保持打开或关闭状态,但是我不知道如何向脚本中添加正确的代码
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.body.style.backgroundColor = "rgb(0,0,0)";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.body.style.backgroundColor = "black";
}
</script>
答案 0 :(得分:0)
根据Cuong le Ngoc的评论,您可以执行类似的操作。加载页面时应运行以下代码:
var key = "menuState";
try
{
/*Determine if the menu was closed, or if element does not exist in localstorage*/
var menuOpen = localStorage.getItem(key);
if (menuOpen === null || menuOpen === 'FALSE')
{
closeNav(); //Close the menu.
}
else
{
openNav(); //Otherwise, the menu was open. Open it.
}
}
catch (ex)
{
console.log("Unable to access local storage to update menu state. " +ex.message);
}
现在在openNav()
和closeNav()
中,您可以看到菜单状态元素的本地存储值。
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.body.style.backgroundColor = "rgb(0,0,0)";
localStorage.setItem(key, 'TRUE'); //Mark menu as open.
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.body.style.backgroundColor = "black";
localStorage.setItem(key, 'FALSE'); //Mark menu as closed.
}