我在 flexbox 容器中有 2 个 DIV,它们并排开始。通过删除其中一个 div,另一个将在容器中居中。
我似乎找不到一种从居中/不居中进行动画过渡的方法。有什么办法吗?
HTML:
<div id='wrap'>
<div id='a'></div>
<div id='b'></div>
</div>
<button id='btna' onclick="toggle('a')">Toggle Red</button>
<br>
<button id='btnb' onclick="toggle('b')">Toggle Green</button>
CSS:
#wrap{
width: 400px;
height: 200px;
border: 1px dashed grey;
display: flex;
justify-content: center;
}
#a{
width: 200px;
height: 200px;
background-color: red;
}
#b{
width: 200px;
height: 200px;
background-color: green;
}
JS:
var displayed = [ true, true ];
function toggle( div )
{
if( div == 'a' )
{
if( displayed[0] )
{
$('#a').fadeOut(500);
}
else
{
$('#a').fadeIn(500);
}
displayed[0] = !displayed[0];
}
else
{
if( displayed[1] )
{
$('#b').fadeOut(500);
}
else
{
$('#b').fadeIn(500);
}
displayed[1] = !displayed[1];
}
}
这是我目前拥有的 jsfiddle:
https://jsfiddle.net/uvyLh8m9/6/
最佳答案
这样做的原因是您的函数 fadeIn 首先在不让 block 消失的情况下降低不透明度,然后才让它消失。
我会这样做:这意味着,让手动淡出并同时减小宽度。您可以选择在 500 毫秒后调用 Element.style.display = 'none';
使用 setTimeout(function(){/*code here*/}, 500);
var displayed = [ true, true ];
function toggle( div )
{
if( div == 'a' )
{
if( displayed[0] )
{
//$('#a').fadeOut(500);
document.getElementById('a').style.opacity = 0;
document.getElementById('a').style.width = '0px';
}
else
{
//$('#a').fadeIn(500);
document.getElementById('a').style.opacity = 1;
document.getElementById('a').style.width = '200px';
}
displayed[0] = !displayed[0];
}
else
{
if( displayed[1] )
{
//$('#b').fadeOut(500);
document.getElementById('b').style.opacity = 0;
document.getElementById('b').style.width = '0px';
}
else
{
//$('#b').fadeIn(500);
document.getElementById('b').style.opacity = 1;
document.getElementById('b').style.width = '200px';
}
displayed[1] = !displayed[1];
}
}
#wrap{
width: 400px;
height: 200px;
border: 1px dashed grey;
display: flex;
justify-content: center;
}
#a, #b {
-webkit-transition:opacity 500ms, width 500ms;
-moz-transition:opacity 500ms, width 500ms;
transition:opacity 500ms, width 500ms;
}
#a{
width: 200px;
height: 200px;
background-color: red;
}
#b{
width: 200px;
height: 200px;
background-color: green;
}
<div id='wrap'>
<div id='a'></div>
<div id='b'></div>
</div>
<button id='btna' onclick="toggle('a')">Toggle Red</button>
<br>
<button id='btnb' onclick="toggle('b')">Toggle Green</button>
关于javascript - 为 2 个 flexbox DIV 设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43849879/