手风琴菜单的小问题(隐藏/显示)

时间:2019-05-12 22:45:07

标签: javascript jquery

好时间。此链接上有一个手风琴菜单:https://www.w3schools.com/code/tryit.asp?filename=G3Z0U159KFM3 (要查看它,您需要单击绿色的“运行”按钮)

这是一个简单的显示/隐藏菜单。如何扩展默认内容并单击可以将其隐藏? (即与当前版本相反)

亲爱的,请帮助解决这个问题。

1 个答案:

答案 0 :(得分:0)

好吧,尽管您描述问题的方式尚不清楚,但我认为您正尝试执行与提供的代码相反的操作,因此您希望默认情况下在单击“内容”菜单时单击在该菜单上,菜单会向后折叠。

首先,您要像这样将.active类默认设置为.ContentsAccordion按钮:

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

然后您要使用以下代码获取菜单的高度并将其放入style div的.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>