gpt4 book ai didi

javascript - 可折叠,具有内容相关的展开大小

转载 作者:行者123 更新时间:2023-11-27 23:23:12 28 4
gpt4 key购买 nike

我使用 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.

我认为真正的解决方案是 this page ,但我无法使其适应我的情况。

最佳答案

No need to calculate dynamic height. Example with button inside button

{}

关于javascript - 可折叠,具有内容相关的展开大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57904274/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com