如何在显示器内转换项目大小的更改:flex;证明内容的合理性:两者之间的空间;div



我有一个display: flex; justify-content: space-between;容器div,里面有两个孩子。第二个子类将被更改为包括(或不包括(具有display: none;的类。当逻辑应用这个类时,它确实会被隐藏,并且第一个子的宽度会增加以适应父div。问题是我不能让第一个子的宽改变来转换,所以当第二个子隐藏或不隐藏时,第一个子会立即改变它的宽度。我希望它的宽度增长到它的全宽,而不是突然变为它的全宽度。

我正在使用React,但它应该只有在css中才有可能,对吧?如果是,我该如何实现这一点?

这是一个可重复的例子:

document.getElementById("toggle").addEventListener("click",function(e){
document.getElementById("second").classList.toggle("hidden")
},false);
.container {
display: flex;
justify-content: space-between;
background: #aaf;
width: 200px;
height: 40px;
align-items: center;
}
.container > *:first-child {
background: #afa;
flex-grow: 1;
}
.container > *:last-child {
display: flex;
justify-content: space-between;
background: #faa;
width: 50px;
}
.container > *:last-child.hidden {
display: none;
}
<div class="container">
<div><span>1st</span></div>
<div id="second" class="hidden">2nd</div>
</div>
<button id="toggle">toggle</button>

为了在宽度之间转换,必须切换宽度值并使用CSS转换属性。不能使用hidden转换宽度,因为这是true或false,没有中间值可在其间转换。

我对你的代码所做的更改:

  • 添加溢出:隐藏在容器上
  • 在宽度之间切换(而不是"隐藏"属性(。这使得能够过渡到工作
  • transition: width 2s添加到两个子项

document.getElementById("toggle").addEventListener("click",function(e){

const width = document.getElementById("second").style.width;
if (width === "" || width === "50px") {
document.getElementById("second").style.width = "0px";
} else {
document.getElementById("second").style.width = "50px";
}
},false);
.container {
display: flex;
justify-content: space-between;

background: #aaf;
width: 200px;
height: 40px;
align-items: center;
overflow: hidden;
}
.container > *:first-child {  
background: #afa;
width: 100%;
transition: width 2s;
}
.container > *:last-child {  
background: #faa;
width: 50px;
transition: width 2s;
}
<div class="container">
<div><span>1st</span></div>
<div id="second">2nd</div>
</div>
<button id="toggle">toggle</button>

最新更新