Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

javascript - Transition flex-grow of items in a flexbox

Is it possible to transition the items in an flexbox? When you click I want all items to collapse except the one that is clicked. The one that is clicked should use all available space from the container.

// only works once!
$(".item").click(function() {
  $(".item").not(this).each(function() {
    $(this).addClass("collapse");
  });
});
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  border: 0;
  overflow: hidden;
}
.container {
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: auto;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.item {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto;
  transition: all 2s;
}
.collapse {
  flex-grow: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="item" style="background: red">a</div>
  <div class="item" style="background: green">b</div>
  <div class="item" style="background: blue">c</div>
  <div class="item" style="background: purple">d</div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

flex-grow is animatable but only if the value is a <number>. However it seems that Google Chrome (v41) doesn't trigger the animation if the value is set to 0.

A workaround for this could be to use a very small value instead — something like 0.0001:

Updated example.

$(".item").click(function() {
    $(".item").addClass("collapse");
    $(this).removeClass("collapse");    
});
html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    border: 0;
    overflow: hidden;    
}

.container {
    flex-basis: auto;
    display: flex;
    flex-direction: column;
    height: 100%;
}

.item {
    flex-grow: 1;
    flex-shrink: 1;
    flex-basis: auto;
    transition: all 2s;
}

.collapse {
    flex-grow: 0.001;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="item" style="background: red">a</div>
    <div class="item" style="background: green">b</div>
    <div class="item" style="background: blue">c</div>
    <div class="item" style="background: purple">d</div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...