javascript - CSS flex 盒 : flex item grow when changing another flex items position

标签 javascript css flexbox

在下面的示例中,我有 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/

相关文章:

html - Safari 6 (iOS 6) flex 布局不换行元素

javascript - 插入数组会导致无限循环

javascript - VueJs Axios - 请求 header

css - 如何垂直居中一个div?

html - 元素宽度的 IE 可计算性问题

html - 导航没有使用 CSS

javascript - Angularjs 使用 jquery ui Accordion - 计时问题

javascript - ng-click 在脚本应答器内不起作用

html - Flexbox 有 max-width 和 max-height 内容并且仍然是响应式的

html - 如何让内容完美的适应flex属性?