我正在使用css和javascript创建可折叠菜单,该菜单是网页的宽度,并对不同类型的支出进行了分类。有一些与特定支出类型相关的子菜单。例如,内部生活成本中,有一个家庭成本子菜单。
我遇到的问题是在其中打开子菜单时增加下拉菜单的高度。在打开子菜单时,由于其内部下拉列表的高度没有增加,因此内容被隐藏。
我使用的javascript函数不会增加打开子菜单时子菜单所在原始下拉菜单的高度。
到目前为止,我已经尝试使用递归来解决此问题,但无济于事。
https://jsfiddle.net/buckler2/vu84wqLa/29/-代码的运行版本
// css下拉
<style>
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: auto;
height: auto;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active, .collapsible:hover {
background-color: #555;
}
.content {
height: 800px;
padding:18px;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
</style>
// HTML示例
<html>
<button class="collapsible">Expenditure</button>
<div class="content">
<button class="collapsible">Living Expenses</button>
<div class="content">
<button class="collapsible">Household expenses</button>
<div class = "content">
//some list of household expenses
</div>
//some list of other living expenses
</div>
//some list of other types of expenditure
</div>
</html>
// 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.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
</script>
答案 0 :(得分:1)
我认为问题在于该功能时无法读取content.scrollHeight值。再次尝试打开菜单时,您会看到它的发生-它会显示全部内容(至少在JSFiddle上)。
将maxHeight值更改为固定数字可以解决此问题:
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = "1000px";
}
});
}