如标题中所述,刷新页面时我的可折叠菜单不会保持关闭状态。每次加载页面时,可折叠菜单都会完全展开,即使在刷新之前它是完全关闭的。这有点问题,因为这个折叠包里有很多东西。
这是它的基本代码:
CSS:
//some code here for the design, background color and stuff that shouldn't matter,
// .active is what I think I need
.active, .collapsible:hover{
background-color: #02538D;
}
HTML:
<button class="collapsible">Tutorials</button>
<div>
<div class="content">
<p>
<?php
//some php here for output of collapsible
?>
</p>
</div>
<div class="content">
<p>
<?php>
//some php here for output of collapsible
?>
</p>
</div>
</div>
JavaScript:
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for(i = 0; i< coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if(content.style.display === "block") {
content.style.display = "none";
}
else {
content.style.display = "block";
}
});
}
</script>
我是 JavaScript 的初学者,所以我很确定这就是错误所在,但我们将不胜感激任何帮助。非常感谢!
最佳答案
在您提供的代码中,菜单的状态永远不会保存 - 因此当页面刷新时,所有内容都只是“重置”为默认值。
一种解决方案当然是使用“display:none;”作为你的CSS中的默认值。这会使菜单在页面刷新时隐藏,但如果您需要它在用户打开它的情况下在刷新之间保持可见,问题仍然存在。
在这种情况下,您可以在切换样式时使用 javascript 设置一个 cookie:
HTML
<button class="collapsible">Collapsible 1</button>
<div>
<div class="menu-item">
<p>Content 1</p>
</div>
<div class="menu-item">
<p>Content 2</p>
</div>
</div>
JavaScript
var coll = document.getElementsByClassName("collapsible");
for(i = 0; i< coll.length; i++) {
var cookies = decodeURIComponent(document.cookie).split(";");
for(i=0;i<cookies.length;i++) {
if(cookies[i] == "menu-state=hide") {
var content = coll[i].nextElementSibling;
content.style.display = "none";
}
}
coll[i].addEventListener("click", function() {
var content = this.nextElementSibling;
if(content.style.display === "block") {
content.style.display = "none";
document.cookie = "menu-state=hide";
}
else {
content.style.display = "block";
document.cookie = "menu-state=display";
}
});
}
https://jsfiddle.net/hxcy1vLr/41/
以上代码将检查是否存在名称和值为“menu-state=hide”的 cookie。如果有,菜单最初将被隐藏。当您点击开关时,此 cookie 将被设置和更改。
关于 JavaScript 中的 cookie: https://www.w3schools.com/js/js_cookies.asp
希望这对您有所帮助!
关于javascript - 刷新时 HTML/Javascript/CSS 可折叠菜单不会保持关闭状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51116629/