如何保持侧面菜单的切换状态
How to keep toggle state of side menu
我需要编辑这个控制滑块菜单的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>
根据 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.
}
我需要编辑这个控制滑块菜单的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>
根据 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.
}