【发布时间】:2020-01-13 10:42:45
【问题描述】:
我正在从一个可折叠对象切换到另一个对象,因为后者具有更好的功能,但作为一个缺点,它似乎更难设置样式。
我想将新过渡动画的样式设置为旧动画。
这里可以看到两个按钮的代码:demo和sn-p
var coll = document.getElementsByClassName("oldcol");
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";
}
});
}
.oldcol {
cursor: help;
border: none;
outline: none;
background: none;
padding: 0;
font-size: 1em;
color: green;
border-bottom: 1px dashed;
transition: .3s;
}
.oldcon {
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);
}
.container {
position: relative;
margin: 0em;
}
.newcon {
display: none;
padding: 0.6em;
margin: 0.5em;
background: #f1f1f1;
box-shadow: 5px 5px 10px 3px inset rgba(0,0,0,0.60);
}
.newcol {
cursor: help;
border: none;
outline: none;
background: none;
padding: 0;
font-size: 1em;
color: green;
border-bottom: 1px dashed;
transition: .3s ease-out;
}
.newcol:focus {
pointer-events: none;
margin-bottom: 3em;
}
.newcol:focus + .newcon
{
display: block;
margin-top: -2.5em;
position: absolute;
left: 0;
right: 0;
}
.fadein {
animation: fadein 1s;
}
@keyframes fadein {
from {opacity:0}
to {opacity:1}
}
Old button: does <button class="oldcol">this</button> work?
<div class="oldcon"><p>Yes!<p/></div>
<hr>
<div class=container>
New button: does <button class="newcol">this</button><span class=newcon>Quite good</span> work?<br>
New button fadein: does <button class="newcol">this</button><span class="newcon fadein">Quite good</span> work?<br>
</div>
到目前为止我已经尝试过什么
- 将
transition: all 3s;放入newconcss(不起作用) - 将以下类添加到
span(并在 html 中写入<span class="newcon visible hidden">)(不起作用)
visibility: visible;
opacity: 1;
transition: opacity 2s linear;
}
.newcon.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s 2s, opacity 2s linear;
}
- 在
span中添加了以下类,它让内容淡入,它可以工作,但我不知道如何为淡出效果做同样的事情。我认为问题在于关闭按钮不需要点击它,但在任何地方点击就足够了(这不是一个好的行为,如何解决它?)。
.fadein {
animation: fadein 1s;
}
@keyframes fadein {
from {opacity:0}
to {opacity:1}
}
有简单的实现
展开/折叠过渡,例如How can I transition height: 0; to height: auto; using CSS?的第一个答案,但我不明白如何在我的情况下应用它。
【问题讨论】:
-
我看到了问题,但没有看到动机。您放弃在 JavaScript 中设置 max-height 并转换 max-height 属性的旧方法的原因是什么?
-
如果它们满足我的需求,我对所有解决方案持开放态度,我是 html/css/js 领域的新手,您能详细解释一下旧方法吗?
-
所以在旧方法中,您只需将
max-height属性设置为0,这意味着元素不能大于没有高度(即不可见)。然后,当您想要显示它时,您的旧方法通过 JavaScript 将max-height设置为等于scrollHeight,这是内部内容的精确高度(以像素为单位)。这似乎正是你想要的,对吧?所以我的问题是:你为什么要改变它? -
啊你在说我的旧按钮的js!好吧,我在这里解释了我想更改按钮的所有原因stackoverflow.com/questions/57846345/…。你是说js也可以和new按钮一起使用?
-
啊,不,你可能是对的,设置
max-height不起作用。我之前在纯文本元素上使用的东西是动画line-height而不是max-height属性。这具有类似的效果,是响应式的,但仅适用于文本。
标签: javascript html css