首页 > 解决方案 > 可折叠与内容相关的扩展大小

问题描述

我使用 CSS 和 JS 编写了一个可折叠按钮,我想将一个按钮嵌套在另一个按钮中。

是否可以动态调整第一个/外部按钮的高度,以便在打开第二个/内部按钮时,第一个按钮的高度增加第二个按钮的高度?

这是我正在处理的代码

coll = document.getElementsByClassName("col");
conn = document.getElementsByClassName("con");
var i;
for (i = 0; i < coll.length; i++) {
    coll[i].setAttribute('data-id', 'con' + i);
    conn[i].setAttribute('id', 'con' + i);
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = document.getElementById(this.getAttribute('data-id'));
        if (content.style.maxHeight) {
            content.style.maxHeight = null;
        } else {
            content.style.maxHeight = content.scrollHeight + "px";
        }
    });
}
.col {
  cursor: help;
  border: none;
  outline: none;
  background: none;
  padding: 0;
  font-size: 1em;
  color: green;
  border-bottom: 1px dashed;
  transition: .3s;
}

.con {
  padding: 0 18px;
  margin: 3px 0;
  max-height: 0;
  overflow: hidden;
  transition: .3s ease-out;
  background-color: #f1f1f1;
  box-shadow: 5px 5px 10px 3px inset rgba(0,0,0,0.60);
}
Does <button class=col>this</button> work?
  <div class=con>
    <p>Yes!</p>
    And what about <button class=col>this</button>?
      <div class=con>
      <p>Yes, but below text is gone!</p>
      </div>
  <p>bye bye</p>
  </div>
There is something to fix.


编辑:懒惰的解决方案

在 javascript 中替换content.scrollHeight为高值,例如9999.

缺点:当按钮打开时,从0到高度的过渡立即开始,并且由于要覆盖的空间很大,所以速度非常快;当按钮关闭时,过渡从最大高度(不是实际高度)开始,因此从最大高度到实际高度在视觉上没有任何反应,从而导致延迟。

coll = document.getElementsByClassName("col");
conn = document.getElementsByClassName("con");
var i;
for (i = 0; i < coll.length; i++) {
    coll[i].setAttribute('data-id', 'con' + i);
    conn[i].setAttribute('id', 'con' + i);
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = document.getElementById(this.getAttribute('data-id'));
        if (content.style.maxHeight) {
            content.style.maxHeight = null;
        } else {
            content.style.maxHeight = 9999 + "px";
        }
    });
}
.col {
  cursor: help;
  border: none;
  outline: none;
  background: none;
  padding: 0;
  font-size: 1em;
  color: green;
  border-bottom: 1px dashed;
  transition: .3s;
}

.con {
  padding: 0 18px;
  margin: 3px 0;
  max-height: 0;
  overflow: hidden;
  transition: .3s ease-out;
  background-color: #f1f1f1;
  box-shadow: 5px 5px 10px 3px inset rgba(0,0,0,0.60);
}
Does <button class=col>this</button> work?
  <div class=con>
    <p>Yes!</p>
    And what about <button class=col>this</button>?
      <div class=con>
      <p>And the transition is super fast</p>
      </div>
  <p>Yes but there is a delay if you close it</p>
  </div>
There is something to fix.

我认为真正的解决方案在这个页面中,但我无法适应我的情况。

标签: javascriptcss

解决方案


无需计算动态高度。 按钮内有按钮的示例

{}

推荐阅读