在下面的示例中,我有 3 个 flex 元素。我想做的是当我改变蓝色的位置时让绿色的生长。我找不到在 CSS 中执行此操作的方法,还是应该在 JS 中手动编写。
$(document).ready(function(){
$("#btnStart").click(function(){
$("#three").addClass("slide-right");
});
});
main {
display: flex;
flex-flow: row no-wrap;
width: 100%;
height: 500px;
justify-content: flex-start;
overflow: hidden;
}
div {
position: relative;
}
#one {
width: 200px;
background-color: red;
}
#two {
flex: 1;
background-color: green;
}
#three {
width: 200px;
background-color: blue;
left: 0;
transition: left 400ms;
}
#three.slide-right {
left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" id="btnStart" value="Start" />
<main>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</main>
最佳答案
因为 div
的位置是相对的
,所以改变 left 属性不会改变布局。
根据MDN article about position :
relative
This keyword lays out all elements as though the element were not positioned, and then adjust the element's position, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned). The effect of position:relative on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined.
如果您不这样做,则不会更改元素本身的宽度,因为您希望它滑动。您可以将其包装在容器中,并更改容器的宽度(参见代码片段)。
$(document).ready(function() {
$("#btnStart").click(function() {
$("#threeContainer").addClass("slide-right");
});
});
main {
display: flex;
flex-flow: row no-wrap;
width: 100%;
height: 500px;
justify-content: flex-start;
overflow: hidden;
}
#one {
width: 200px;
background-color: red;
}
#two {
flex: 1;
background-color: green;
}
#threeContainer {
width: 200px;
transition: width 400ms;
}
#threeContainer.slide-right {
width: 0;
}
#three {
height: 100%;
width: 200px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" id="btnStart" value="Start" />
<main>
<div id="one"></div>
<div id="two"></div>
<div id="threeContainer">
<div id="three">
I'm an example text that won't change when #three slides
</div>
</div>
</main>
关于javascript - CSS flex 盒 : flex item grow when changing another flex items position,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40958466/