jQuery toggle (Click to show one div while hiding

2019-01-18 05:37发布

The basic idea is that I have a bunch of div's in which each can be toggled (show/hide).

When one div is toggled I'd like for other div's that are currently being shown to hide, thus only allowing one single div to be shown at a time.

In addition I'd like to be able to click outside the element to hide the open div as well.

Just to make things clearer I provided an example which currently does everything I want except closing a div when opening another (Only one div open at a time functionality):

$(document).ready(function(){

  $('div.dropdown').each(function() {
    var $dropdown = $(this);

    $("a.dropdown-link", $dropdown).click(function(e) {
      e.preventDefault();
      $("div.dropdown-container", $dropdown).toggle();
      return false;
    });

});
    
  $('html').click(function(){
    $("div.dropdown-container").hide();
  });
     
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="dropdown-1" class="dropdown dropdown-processed">
  <a class="dropdown-link" href="#">Options</a>
  <div class="dropdown-container" style="display: none;">
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
  </div>
</div>

<div id="dropdown-2" class="dropdown dropdown-processed">
  <a class="dropdown-link" href="#">Options</a>
  <div class="dropdown-container" style="display: none;">
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
  </div>
</div>

<div id="dropdown-3" class="dropdown dropdown-processed">
  <a class="dropdown-link" href="#">Options</a>
  <div class="dropdown-container" style="display: none;">
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
  </div>
</div>

标签: jquery toggle
7条回答
对你真心纯属浪费
2楼-- · 2019-01-18 06:03
    $(document).ready(function(){

      $('div.dropdown').each(function() {
        var $dropdown = $(this);

        $("a.dropdown-link", $dropdown).click(function(e) {
          e.preventDefault();
          $("div.dropdown-container").hide();
            if($("div.dropdown-container", $dropdown).hide()){
                $("div.dropdown-container", $dropdown).show();
            }else{
                $("div.dropdown-container", $dropdown).hide();
            }
          return false;
        });

    });

      $('html').click(function(){
        $("div.dropdown-container").hide();
      });

    });

http://jsfiddle.net/NFTFw/40/

查看更多
登录 后发表回答