我怎样才能阻止我的中心 div 在我 SlideUp 另一个 div 之后改变位置?

How can I stop my center div from changing position after I SlideUp another divs?

我正在创建带有 <header><section> 的简单页面。在 section 中,我有 3 个 div,我用 display: flex;justify-content: space-between.

定位它们

问题是我还在其中两个(极端的)上使用了 JS slideToggle()。他们上去后正在改变我中心的布局div。我该怎么做才能让我的中心 div 在其中一个中心向上滑动后不改变位置?

$(document).ready(function() {
  $('#playlist').click(function() {
    $('#nav').slideToggle();
  });
});

$(document).ready(function() {
  $('#songs').click(function() {
    $('#listSongs').slideToggle();

  });
});
section {
  display: flex;
  justify-content: space-between;
}

#listSongs {
  margin-top: 50px;
  height: 550px;
  background-color: black;
  border-radius: 5px;
  font-size: 25px;
  width: 200px;
}

#listSongs p {
  margin-top: 5px;
  width: 200px;
  text-align: center;
  overflow: hidden;
  height: 35px;
  line-height: 50px;
  color: white;
}

#player {
  color: red;
}

#nav {
  margin-top: 50px;
  height: 550px;
  background-color: black;
  border-radius: 20px;
  width: 200px;
}

.hidden {
  margin-top: 50px;
  height: 550px;
  background-color: black;
  border-radius: 20px;
  width: 200px;
  visibility: hidden;
}

#nav p {
  text-align: center;
}

#nav ul {
  list-style-type: none;
  text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <div id="listSongs">
    <p>Authors:</p>
    <div class="after"></div>
  </div>
  <div id="player">
    <p>something</p>
  </div>
  <div id="nav">
    <p>something</p>
  </div>
</section>

问题是因为当 slideUp/slideDown/slideToggle 方法完成时,它们在目标元素上设置了 display: none。这就是导致页面布局发生变化的原因。

要解决并改进动画,您可以改用 CSS。使用 transition 属性 为 height 设置设置动画。然后你可以切换 class ,它在目标元素上设置 height: 0 。试试这个:

$(document).ready(function() {
  $('#playlist').click(function() {
    $('#nav').toggleClass('hide');
  });

  $('#songs').click(function() {
    $('#listSongs').toggleClass('hide');
  });
});
body { background-color: #CCC; }
section {
  display: flex;
  justify-content: space-between;
}

section > div.panel {
  margin-top: 50px;
  height: 550px;
  background-color: black;
  border-radius: 5px;
  font-size: 25px;
  width: 200px;
  transition: height 0.4s;
  overflow: hidden;
}

section > div.panel.hide {
  height: 0;
}

section > div.panel p {
  margin-top: 5px;
  width: 200px;
  text-align: center;
  overflow: hidden;
  height: 35px;
  line-height: 50px;
  color: white;
}

#player {
  color: red;
}

#nav {
  border-radius: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="playlist">Playlist</button>
<button id="songs">Songs</button>
<section>
  <div id="listSongs" class="panel">
    <p>Authors:</p>
    <p>lorem ipsum</p>
    <div class="after"></div>
  </div>
  <div id="player">
    <p>something</p>
  </div>
  <div id="nav" class="panel">
    <p>something</p>
  </div>
</section>

请注意,我还重新安排了一些 CSS 以使其更通用且重复更少。