正如标题中所述,刷新页面时,我的可折叠菜单不会保持关闭状态。每次加载页面时,可折叠菜单都会完全展开,即使在刷新之前完全关闭也是如此。这有点问题,因为这个可折叠的东西很多。
这是它的基本代码:
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>
爪哇脚本
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
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句