首页 > 解决方案 > 在我 SlideUp 另一个 div 后,如何阻止我的中心 div 改变位置?

问题描述

我正在使用 a<header>和 a创建简单的页面<section>。在section我有 3 个 div 中,我用display: flex;和定位它们justify-content: space-between

问题是我也在slideToggle()其中两个(极端的)上使用了 JS。在它们上升后,它正在改变我的中心 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>

标签: javascripthtmljquerycsslayout

解决方案


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

要解决此问题并改进动画,您可以改用 CSS。使用该transition属性为设置设置动画height。然后,您可以切换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 以使其更通用且重复更少。


推荐阅读