css 刷新后保持 accordion 打开

7fhtutme  于 2023-04-01  发布在  其他
关注(0)|答案(3)|浏览(121)

我有一个带有 accordion 菜单的sidenav,但是当我刷新或转到另一个页面时,它会关闭。如何在这些操作后保持打开状态?这里的CSS示例:https://jsfiddle.net/ag9q1tvc/
JavaScript:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var parent = this.parentElement;
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
      parent.style.maxHeight = parseInt(parent.style.maxHeight) + panel.scrollHeight + "px";
    } 
  });
}

HTML:

<div class='sidenav'>
  <button class='accordion'><i class='fa fa-star' aria-hidden='true'></i>&nbsp; FAV</button>
  <button class='accordion'><i class='fa fa-th-large' aria-hidden='true'></i>&nbsp; SALES</button>
  <div class='panel'>
      <a href='item1.php'>&emsp;ITEM 1</a>
       <a href='item2.php'>&emsp;ITEM 2</a>
</div>

我在其他答案中找不到我的问题的确切方法。谢谢!

6kkfgxo0

6kkfgxo01#

你需要将accordion状态存储在某个地方,它可以是sessionStorage或localStorage,也称为cookie。对于我来说,sessionStorage是最好的方法,下面是一个例子:

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var parent = this.parentElement;
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
      sessionStorage.setItem(parent.id, ""); // store it as closed
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
      parent.style.maxHeight = parseInt(parent.style.maxHeight) + panel.scrollHeight + "px";
      sessionStorage.setItem(parent.id, "open"); // store it as open
    }
  });

  // here we are getting state from sessionStorage
  var parent = acc[i].parentElement;
  if (sessionStorage.getItem(parent.id) === "open") {
    parent.querySelector(".panel").style.maxHeight = parent.querySelector(".panel").scrollHeight + "px";
    parent.style.maxHeight = parseInt(parent.style.maxHeight) + parent.querySelector(".panel").scrollHeight + "px";
    acc[i].classList.add("active");
  }
}

请注意,它将存储状态,直到浏览器关闭,否则您可以使用Cookie。

gcuhipw9

gcuhipw92#

:target Selector和锚标签(无JS)

如果一个元素的id等于url后面的hash(#),则:target选择器匹配。由于浏览器通过reload或navigation来保存hash,因此这将持久化url中的accordion的状态。

  • PRO:无需JavaScript,跨浏览器兼容
  • 缺点:如果你需要#来做其他事情(比如单页路由),这不是一个选择。
#accordion {
  display: blocK;
  border: 2px solid blue;
}

#accordion > .content {
  display: none;
}

#accordion:target > .content {
  display: block;
}
<a href="#accordion">open</a>
<a href="#">close</a>

<a id="accordion">
  <div class="content">
    Content
  </div>
</a>
hof1towb

hof1towb3#

你可以尝试使用本地存储,它是一个变量,存储在浏览器该高速缓存中
System. out. println();
你可以在这里看到更多信息:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

相关问题