如何为单页应用程序重新排列div

时间:2018-09-26 23:21:50

标签: javascript html css

我正在构建一个单页Web应用程序。在这个文件中,我希望启动时显示特定的div。也许用户然后会按下一个按钮,然后一个新的div将取代它。

现在,在这种情况下,我正在使用js隐藏一个div并显示另一个div。问题是,新的div出现在页面的下方(因为它是在第一个div之后写入html文件中的)。

当用户在div之间来回导航时,如何使用javascript简单地将一个div替换为另一个div?这可能并建议吗?

/* JS
When #firstButton is pressed, replace div #first with div #second
When #secondButton is pressed, replace the div #second with div #first
*/
#second {
  visibility: hidden;
}
<div id="first">
  <h1>First Page</h1>
  <button id="firstButton">Go to second page</button>
</div>


<div id="second">
  <h1>Second Page</h1>
  <button id="secondButton">Go to first page</button>
</div>

2 个答案:

答案 0 :(得分:2)

使用visibility: hidden会使您的元素仍然占用空间,这就是为什么您的“页面”似乎没有改变位置的原因。

切换到display: none,可以使用jQuery的.show().hide()轻松切换,就像这样:

$("#firstButton").on("click", function() {
  $("#first").hide();
  $("#second").show();
});

$("#secondButton").on("click", function() {
  $("#first").show();
  $("#second").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="first">
  <h1>First Page</h1>
  <button id="firstButton">Go to second page</button>
</div>

<div id="second" style="display: none;">
  <h1>Second Page</h1>
  <button id="secondButton">Go to first page</button>
</div>

答案 1 :(得分:1)

如果您不想使用jQuery:

document.getElementById("firstButton").addEventListener("click", () => {
  document.getElementById("first").style.display="none";
  document.getElementById("second").style.display="block";
}, false);

document.getElementById("secondButton").addEventListener("click", () => {
  document.getElementById("first").style.display="block";
  document.getElementById("second").style.display="none";
}, false);
<div id="first">
  <h1>First Page</h1>
  <button id="firstButton">Go to second page</button>
</div>


<div id="second" style="display:none">
  <h1>Second Page</h1>
  <button id="secondButton">Go to first page</button>
</div>