Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

html - Show/Hide script using javascript

I have a show/hide script that I am using for a menu. When I click a main link it brings up a list below it. I was wondering if there is a way to alter it a bit so that when I click the link it opens but when I click the next one it closes the other one instead of leaving them all open unless you click it again to close.

Here is my script:

<script type="text/javascript">
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
</script>


<a href="#" onclick="toggle_visibility('list1');">
       <p>List One</p>
       </a>
       <div id="list1" style="display:none;">
         <ul>
           <li>Item One</li>
           <li>Item Two</li>
           <li>Item Three</li>
         </ul>
       </div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Suppose this is your code:

<a href="#" onclick="toggle_visibility('list1');">
  <p>List One</p>
</a>
<div id="list1" style="display:none;">
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
  </ul>
</div>
<a href="#" onclick="toggle_visibility('list2');">
  <p>List Two</p>
</a>
<div id="list2" style="display:none;">
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
  </ul>
</div>

Change it to this:

<a href="#" onclick="toggle_visibility('list1');">
  <p>List One</p>
</a>
<div id="list1" class="alist" style="display:none;">
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
  </ul>
</div>
<a href="#" onclick="toggle_visibility('list2');">
  <p>List Two</p>
</a>
<div id="list2" class="alist" style="display:none;">
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
  </ul>
</div>

And make your JavaScript this:

function toggle_visibility(id) {
    var list = document.getElementsByClassName("alist");
    for (var i = 0; i < list.length; i++) {
        list[i].style.display = 'none';
    }
    var e = document.getElementById(id);
    if(e.style.display == 'block') {
        e.style.display = 'none';
    } else {
        e.style.display = 'block';
    }
}

Here's a JSFiddle.

Instead of using plain JavaScript for this, I suggest you use jQuery.

Here's how I would do it in jQuery:

function toggle_visibility(id) {
  $(".list").hide();
  $("#" + id).toggle();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...