我正在寻找一种在同级容器的内容更新时动画化Flex容器高度变化的方法。
以下是flex容器的一个非常简单的示例。请尝试单击按钮toggleText来查看它的实际效果。进行同级更改后,是否有任何方法可以对红色容器的高度进行动画处理?我尝试为flex进行过渡,但在我的情况下不起作用。
谢谢!
var i = 0;
var toggleText = function() {
document.querySelector('p').innerHTML = text[(i++) % 2];
}
var text = [
"Some short text here.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."]
.container {
height: 140px;
width: 400px;
border: 1px solid black;
padding: 10px;
display: flex;
flex-flow: column;
}
.image {
background-color: bisque;
flex: 1 1 auto;
display: flex;
border: 1px solid red;
}
<button onclick="toggleText()">toggleText</button>
<div class="container">
<p></p>
<div class="image"></div>
</div>
答案 0 :(得分:1)
有几种方法可以做到这一点。我想到了以下想法。我希望这个对你有用。希望方便。
var i = 0,
hidden = document.querySelector('#hidden p'),
visible = document.querySelector('#visible p'),
hiddenHeight = 0,
content;
var toggleText = function() {
content = text[(i++) % 2];
hidden.innerHTML = content;
hiddenHeight = hidden.offsetHeight;
hidden.innerHTML = "";
visible.style.height = hiddenHeight+"px";
visible.innerHTML = content;
}
var text = [
"Some short text here.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."]
.container {
height: 140px;
width: 400px;
border: 1px solid black;
padding: 10px;
display: flex;
flex-flow: column;
transition: all 500ms;
}
.container p{
transition: all 500ms;
}
.image {
background-color: bisque;
flex: 1 1 auto;
display: flex;
border: 1px solid red;
}
#hidden {
height:0!important;
overflow:hidden!important;
}
#hidden p{
visibility: hidden;
opacity: 0;
transition: all 500ms;
}
<button onclick="toggleText()">toggleText</button>
<div class="container">
<div id="hidden">
<p></p>
</div>
<div id="visible">
<p style="height:0"></p>
</div>
<div class="image"></div>
</div>
您可以根据需要更改animation time and delays。