首页 > 解决方案 > 隐藏另一个 div 时移动一个 div

问题描述

div#content {
  position: relative;
  width: 100%;
  border: 1px solid black;
  height: 500px;
  bottom: 0px;
}

div#menu {
  position: absolute;
  height: 125px;
  width: 100%;
  border: 1px solid black;
  bottom: 0px;
  line-height: 125px;
  text-align: center;
}

div#recenter {
  line-height: 50px;
  text-align: center;
  border: 1px solid black;
  border-radius: 30px;
  position: absolute;
  margin: 10px;
  padding: 0px 20px;
  bottom: 180px;
  background-color: aliceblue;
}

div#geolocation {
  line-height: 50px;
  text-align: center;
  border: 1px solid black;
  position: absolute;
  margin: 10px;
  bottom: 125px;
  background-color: aliceblue;
}
<div id="content">
  <div id="recenter">Re-center</div>
  <div id="geolocation">My address is : 3958 Heron Way - Oregon 97351</div>
  <div id="menu" onclick="document.getElementById('geolocation').style.display = 'none';">MENU (CLICK ME)</div>
</div>

#geolocation目前,当我在 javascript 中隐藏块时,#recenter按钮不会移动。

我想要的是,当我运行以下 jQuery 命令时:( $('#geolocation').hide(); 或在 js 中:)document.getElementById('geolocation').style.display = 'none';按钮#recenter移动到底部(#geolocation块所在的位置)

怎么做 ?

标签: javascripthtmlcss

解决方案


不要绝对定位元素,利用 flexbox 布局和对齐选项。

div#content {
  position: relative;
  width: 80%;
  margin: 1em auto;
  border: 1px solid black;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: flex-start;
}

div#menu {
  height: 50px;
  width: 80%;
  border: 1px solid black;
  text-align: center;
  margin: 0 auto;
}

div#recenter {
  line-height: 20px;
  text-align: center;
  border: 1px solid black;
  border-radius: 30px;
  margin: 10px;
  padding: 0px 10px;
  background-color: aliceblue;
}

div#geolocation {
  line-height: 20px;
  text-align: center;
  border: 1px solid black;
  margin: 10px;
  background-color: aliceblue;
}
<div id="content">
  <div id="recenter">Re-center</div>
  <div id="geolocation">My address is : 3958 Heron Way - Oregon 97351</div>
  <div id="menu" onclick="document.getElementById('geolocation').style.display = 'none';">MENU (CLICK ME)</div>
</div>


推荐阅读