首页 > 解决方案 > Little problem with accordion-menu (hide/show)

问题描述

Good time. There is an accordion menu at this link: https://www.w3schools.com/code/tryit.asp?filename=G3Z0U159KFM3 (to see it, you need to click on the green "Run" button)

This is a simple show / hide menu. How to make the default content was expanded and by clicking could hide it? (i.e. the opposite of the current one)

Dears, please help with this problem.

标签: javascriptjquery

解决方案


好吧,虽然您描述问题的方式不清楚,但我认为您正在尝试与您提供的代码相反,因此您希望默认显示“内容”菜单,当您单击它时菜单会向后折叠。

首先,您希望将.active类默认设置为.ContentsAccordion按钮,如下所示:

<button class="ContentsAccordion active">Contents</button>

然后你想得到你的菜单的高度,并用这个代码把它放到你的 div的style元素中:.ContentsPanel

var pan = document.getElementsByClassName("ContentsPanel");
pan[0].setAttribute('style', 'max-height: ' + pan[0].scrollHeight + 'px;');

并且您的其余代码不需要任何更改。

下面的工作示例:

<style>
.ContentsAccordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 18px;
  transition: 0.4s;
}

button.ContentsAccordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

button.ContentsAccordion.active:after {
    content: '\2212';
}

.active, .ContentsAccordion:hover {
  background-color: #ccc;
}

.ContentsPanel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  border: 1px #ccc solid;
}

.ContentsAccordionP {
  font-size: 16px;
}
</style>

<button class="ContentsAccordion active">Contents</button>
<div class="ContentsPanel">
  <a href="#"><p class="ContentsAccordionP">Some text 1</p></a>
  <a href="#"><p class="ContentsAccordionP">Some text 2</p></a>
  <a href="#"><p class="ContentsAccordionP">Some text 3</p></a>
</div>


<script>
var acc = document.getElementsByClassName("ContentsAccordion");
var i;

var pan = document.getElementsByClassName("ContentsPanel");
pan[0].setAttribute('style', 'max-height: ' + pan[0].scrollHeight + 'px;');

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


推荐阅读