首页 > 解决方案 > 截面尺寸随可折叠而变化

问题描述

我有多个可折叠的 div,我想将它们放在一个部分中

我尝试了一个脚本,该脚本在单击可折叠按钮时更改该部分的大小,但根本没有反应。

var drop = document.getElementsByClassName("drop");
var panel = document.getElementById("panel");
var i;
	
for (i = 0; i < drop.length; i++) {
  drop[i].addEventListener("click", function() {
  this.classList.toggle("active");
  var collapse = this.previousElementSibling;
  if (collapse.style.maxHeight) {
    collapse.style.maxHeight = null;
    } else {
    collapse.style.maxHeight = collapse.scrollHeight + "px";
    }
  });
}
for (i = 0; i < drop.length; i++) {
  drop[i].addEventListener("click", function() {
  if (panel.style.maxHeight) {
    panel.style.maxHeight = null;
    } else {
    panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}
#panel	{
	background-color: black;
	float: center;
	position: relative;
	width: 500px;
	height: 500px
}

#box1	{
	background-color: red;
	position: absolute;
	bottom: 0;
	left: 0;
}

#box2	{
	background-color: yellow;
	position: absolute;
	bottom: 0;
	right: 0;
	float: right;
}

.drop {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

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

.collapse {
  padding: 0 18px;
  background-color: red;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
<div id=panel>
	<div id="box1">
		<br>this is red</br>
		<div class="collapse">
			<p>a drop</p>
		</div>
		<button class="drop">view more</button>
	</div>
	<div id="box2">
		<br>this is yellow</br>
		<div class="collapse">
			<p>a drop</p>
		</div>
		<button class="drop">view more</button>
	</div>
</div>

我希望整个部分在折叠被触发时向下扩展,相反,什么也没有发生。

标签: javascripthtmlcss

解决方案


推荐阅读