简体   繁体   中英

Switching between two div elements using Javascript

I have the following code for going from div "mainFrameOne" to div "mainFrameTwo". However, it cannot go back to mainFrameOne after changing to mainFrameTwo. And I want it to be able to keep switching back and forth. How would I best accomplish this?

HTML :

<div id="mainFrameOne">
    <p>mainFrameOne</p>
</div>
<div id="mainFrameTwo" style="display:none;">
    <p>mainFrameTwo</p>
</div>
<button onclick="myFunction()">Click me</button>

JS :

function myFunction() { 
    document.getElementById("mainFrameOne").style.display="none"; 
    document.getElementById("mainFrameTwo").style.display="block"; 
}

Add condition to check if the div is visible then hide it and show the other one if else do the reverse :

function myFunction() {
   var mainFrameOne = document.getElementById("mainFrameOne"); 
   var mainFrameTwo = document.getElementById("mainFrameTwo");

   mainFrameOne.style.display = (
       mainFrameOne.style.display == "none" ? "block" : "none"); 
   mainFrameTwo.style.display = (
       mainFrameTwo.style.display == "none" ? "block" : "none"); 
}

Hope this helps.


 function myFunction() { var mainFrameOne = document.getElementById("mainFrameOne"); var mainFrameTwo = document.getElementById("mainFrameTwo"); mainFrameOne.style.display = ( mainFrameOne.style.display == "none" ? "block" : "none"); mainFrameTwo.style.display = ( mainFrameTwo.style.display == "none" ? "block" : "none"); } 
 <div id="mainFrameOne"> <p>mainFrameOne</p> </div> <div id="mainFrameTwo" style="display:none;"> <p>mainFrameTwo</p> </div> <button onclick="myFunction()">Click me</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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