gpt4 book ai didi

Javascript SideBar 在页面更改时保持打开状态

转载 作者:行者123 更新时间:2023-11-29 22:49:02 28 4
gpt4 key购买 nike

我创建了一个边栏,它通过一个简单的 javascript 开关打开,如果用户打开了边栏,我想在页面更改期间保持打开状态。

当点击 openMenu 按钮时,它运行切换功能。

HTML:

<h2 onclick="toggleSidebar()"><a href="#">Table of
Contents</a></h2>

<nav id="sidenav">
<div id="top-sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="toggleSidebar()">Table of Contents
&ThickSpace;&times;</a>
</div>
<ul class="subnav">
<li>
<a href="chapter/1.html">Chapter 1
<p>Down the Rabbit-Hole</p>
</a>

</li>
...
</ul>
</nav>

JavaScript:

function toggleSidebar() {
document.getElementById("sidenav").classList.toggle("active");
document.getElementById("main").classList.toggle("sideNavActive");
document.getElementById("buttonHomepage").classList.toggle("sideNavTopBar");
document.getElementById("prevChapter").classList.toggle("sideNavActive");

}

最佳答案

方法如下,

在您的正文或文档中准备好按照下面的方式实现,

HTML

<body onload=loadMenu()>

document.addEventListener('DOMContentLoaded', (event) => {
loadMenu()
})

或者 - 如果你有 jQuery

$(document).ready(function() {
loadMenu();
});

脚本

function loadMenu() {
if(getLocalStorage("openMenu") == "true") {
toggleSidebar()
}
}

function toggleSidebar() {
document.getElementById("sidenav").classList.toggle("active");
document.getElementById("main").classList.toggle("sideNavActive");
document.getElementById("buttonHomepage").classList.toggle("sideNavTopBar");
document.getElementById("prevChapter").classList.toggle("sideNavActive");
/*for toggle the menu on localstorage*/
(getLocalStorage("openMenu") == "true" ? setLocalStorage("openMenu", false) : setLocalStorage("openMenu", true)); //wil toggle and trigger menu when modal opened
}

function setLocalStorage(key, value) {
if(typeof(Storage) !== "undefined")
{
window.localStorage.setItem(key, value);
}
}

function getLocalStorage(key) {
if(typeof(Storage) !== "undefined")
{
return window.localStorage.getItem(key)
}
}

关于Javascript SideBar 在页面更改时保持打开状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57766802/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com