简体   繁体   English

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

[英]How to rearrange divs for single page application

I'm building a single-page web app. 我正在构建一个单页Web应用程序。 In this one file, I want a specific div to be shown on startup. 在这个文件中,我希望启动时显示特定的div。 Perhaps the user will then press a button, and a new div will replace it. 也许用户然后会按下一个按钮,而新的div将取代它。

Right now, I'm using js to hide one div and show another in this case. 现在,在这种情况下,我正在使用js隐藏一个div并显示另一个div。 The problem is, the new div appears further down the page (as it is written in the html file after the first div). 问题是,新的div出现在页面的下方(因为它是在第一个div之后写入html文件中的)。

How can I, using javascript, simply replace one div with another as the user navigates back and forth between the divs? 当用户在div之间来回导航时,如何使用javascript简单地将一个div替换为另一个div? Is this possible and recommended? 这可能并建议吗?

 /* 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> 

Using visibility: hidden is causing your elements to still take up space, which is why your "pages" don't appear to change places. 使用visibility: hidden会导致您的元素仍然占用空间,这就是为什么您的“页面”似乎不会更改位置的原因。

Switch to display: none , which can be easily toggled with jQuery's .show() and .hide() like so: 切换到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> 

If you don't want to use jQuery: 如果您不想使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM