Seb*_*rth 5 css animation transition slide css-transitions
我用来transition: height 500ms向元素添加动画,该元素通过按钮从height: 0to滑动打开height: 100px,反之亦然。
由于元素的内容是动态添加的,我不知道它的大小,我想改为切换到height: fit-content。这样,元素将始终具有正确的大小来显示其内容。
可悲的是,这会禁用动画。
如何将动画与大小适合其内容的 div 元素结合在一起?
以下代码段显示了行为:
document.querySelector('button')
.addEventListener(
'click',
() => document.querySelectorAll('div')
.forEach(div => div.classList.toggle('closed')));Run Code Online (Sandbox Code Playgroud)
div {
background-color: lightblue;
border: 1px solid black;
overflow: hidden;
transition: height 500ms;
}
div.closed {
height: 0 !important;
}
div.div1 {
height: 100px;
}
div.div2 {
height: fit-content;
}Run Code Online (Sandbox Code Playgroud)
<button type="button">toggle</button>
<h1>'height: 100px' => 'height: 0'</h1>
<div class="div1">
some text<br />
even more text<br />
so much text
</div>
<br>
<h1>'height: fit-content' => 'height: 0'</h1>
<div class="div2">
some text<br />
even more text<br />
so much text
</div>Run Code Online (Sandbox Code Playgroud)
Ros*_*kow 11
正如 Mishel 所说,另一个解决方案是使用 max-height。这是该解决方案的一个工作示例。
关键是在完全展开时近似最大高度,然后过渡就会平滑。
希望这可以帮助。
https://www.w3schools.com/css/css3_transitions.asp
document.querySelector('button')
.addEventListener(
'click',
() => document.querySelectorAll('div')
.forEach(div => div.classList.toggle('closed')));Run Code Online (Sandbox Code Playgroud)
div {
background-color: lightblue;
border: 1px solid black;
overflow-y: hidden;
max-height: 75px; /* approximate max height */
transition-property: all;
transition-duration: .5s;
transition-timing-function: cubic-bezier(1, 1, 1, 1);
}
div.closed {
max-height: 0;
}Run Code Online (Sandbox Code Playgroud)
<button type="button">toggle</button>
<h1>'height: 100px' => 'height: 0'</h1>
<div class="div1">
some text<br />
even more text<br />
so much text
</div>
<br>
<h1>'height: fit-content' => 'height: 0'</h1>
<div class="div2">
some text<br />
even more text<br />
so much text
</div>Run Code Online (Sandbox Code Playgroud)
一种可能的解决方案(尽管并不完美)是用动画font-size代替height.
另一种解决方案可能是动画max-height而不是height. 你可以使用max-height300px 或 500px。但如果你需要更多,那就不太好看了。
我在这里设置字体大小的动画。
希望有帮助。谢谢。
document.querySelector('button')
.addEventListener(
'click',
() => document.querySelectorAll('div')
.forEach(div => div.classList.toggle('closed')));Run Code Online (Sandbox Code Playgroud)
div {
background-color: lightblue;
border: 1px solid black;
overflow: hidden;
transition: font-size 500ms;
}
div.closed {
font-size: 0 !important;
}
div.div1 {
font-size: 14px;
}
div.div2 {
font-size: 14px;
}Run Code Online (Sandbox Code Playgroud)
<button type="button">toggle</button>
<h1>'height: 100px' => 'height: 0'</h1>
<div class="div1">
some text<br />
even more text<br />
so much text
</div>
<br>
<h1>'height: fit-content' => 'height: 0'</h1>
<div class="div2">
some text<br />
even more text<br />
so much text
</div>Run Code Online (Sandbox Code Playgroud)