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
450 views
in Technique[技术] by (71.8m points)

javascript - How to toggle between two divs

I am trying to toggle between two divs. For example, onload, I want the left content to show and the right content will remain hidden. If I click the right div, I want the left content to hide and the right content to appear and vise versa. I am very new to javascript but here is what I have. I can't seem to get it to work. Please help...

Here is my HTML code:

<div onclick="toggle_visibility('left');">
  Left
</div>

<div onclick="toggle_visibility('right');">
  Right
 </div>


 <div id="left" style="display: block;">
    This is the content for the left side
 <div>

 <div id="right" style="display: none;">
    This is the content for the ride side
 </div>

Here is the Javascript I am using:

<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>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Live demo: http://jsfiddle.net/PauWy/1/

HTML:

<p id="toggle">
    <span> Left </span>
    <span> Right </span>
</p>

<div id="left"> LEFT CONTENT </div>
<div id="right"> RIGHT CONTENT </div>

JavaScript:

$('#toggle > span').click(function() {
    var ix = $(this).index();

    $('#left').toggle( ix === 0 );
    $('#right').toggle( ix === 1 );
});

CSS (to hide the right DIV onload):

#right { display:none; } 

Put the JavaScript code at the bottom of the page.

    <script>
        $(function() {        
            // put jQuery code here    
        });
    </script>    
</body>

Notice how the SCRIPT element is located at the end of the BODY element. Also, notice that the jQuery code should be inside the ready handler: $(function() { ... code ... });


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

...