javascript - 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.
解决方案
好吧,虽然您描述问题的方式不清楚,但我认为您正在尝试与您提供的代码相反,因此您希望默认显示“内容”菜单,当您单击它时菜单会向后折叠。
首先,您希望将.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>
推荐阅读
- powercli - 无法从 powercli 创建数据存储 Starwind
- string - LUA (ESP8266) 如何从字符串调用/输入模块命令
- wordpress - 替换 HTML 输出中的 Wordpress URL 域(用于 SEO 优化)
- docusignapi - 通过 Salesforce 在 Docusign 中自动静默配置和激活我们的用户
- django - 文件和序列化程序的解码问题
- informix - 如何计算不同的多列
- reactjs - 检查登录错误 ReferenceError: currentuser is not defined at app.js:34
- android - 我的字符串变量未分配 TextRecognition 输出
- java - 无法从服务器发送的类中获取注释 - Java
- reactjs - 使用反应时访问“本地”文件以在 Web Audio API 中使用的最佳方式?