简体   繁体   中英

Show only one div in main page JavaScript

I am making a project for my school, and I need a main page where I can display all my different divs, but only one at a time and always show one. I dont understand much of js, but I got that code who does the job, but if I click the same button it will hidde it, and I dont want to close it, just to stay in the same div.

It will act upon itself, my main page.

HTML:

<ul class="sidenav">
  <li><a class="active" href="javascript:void(null)" onclick="showhide('home');">Home</a></li>
  <li><a href="javascript:void(null)" onclick="showhide('forms');">Forms</a></li>
</ul>

CSS:

div.content {
    margin-left: 20%;
    padding: 1px 16px;
    height: 1000px;
    display: none;
}

JavaScript:

var divState = {};
function showhide(id) {
    if (document.getElementById) {
        var divid = document.getElementById(id);
        divState[id] = (divState[id]) ? false : true;
        for (var div in divState){
            if (divState[div] && div != id){
                document.getElementById(div).style.display = 'none';
                divState[div] = false;
            }
        }
        divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
    }
}

1st use var divState = ['home', 'forms']; hold all your div.

2nd when you click hide all other div, show the clicked one.

3rd call showhide('home') on page load.

 div.content { margin-left: 20%; padding: 1px 16px; height: 1000px; display: none; } 
 <ul class="sidenav"> <li><a class="active" href="javascript:void(null)" onclick="showhide('home');">Home</a></li> <li><a href="javascript:void(null)" onclick="showhide('forms');">Forms</a></li> </ul> <div id="home"> home div </div> <div id="forms"> forms div </div> <script> var divState = ['home', 'forms']; function showhide(id) { if (document.getElementById) { var divid = document.getElementById(id); for (var d in divState) { if (divState[d] != id) { document.getElementById(divState[d]).style.display = 'none'; } else { divid.style.display = 'block'; } } } } showhide('home'); </script> 

If you only want to show the div on click, but not hide it when the same link is clicked again, just replace the last line of the showHide() function to always show the div instead of toggling it.

var divState = {};
function showhide(id) {
    if (document.getElementById) {
        var divid = document.getElementById(id);
        divState[id] = (divState[id]) ? false : true;
        for (var div in divState){
            if (divState[div] && div != id){
                document.getElementById(div).style.display = 'none';
                divState[div] = false;
            }
        }
        divid.style.display = 'block';
    }
}

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