show div and hide existing div if open with jQuery?

♀尐吖头ヾ 提交于 2019-12-12 02:55:28

问题


I have two divs which are hidden by default. The user then reveals the div on click. If a div is already open, and the user clicks to reveal the other div, I want the current div to hide, and show the new div.

My current code is this..

HTML

<div class="menu">MENU</div>
<div class="search">SEARCH</div>

<div class="menu-box">MENU BOX</div>
<div class="search-box">SEARCH BOX</div>

CSS

 .menu, .search {
      display:inline-block;
      cursor:pointer;
    }

    .menu, .search, .menu-box, .search-box  {
      padding:20px;
      background-color: #ccc;
      margin-right:10px;  
    }

    .menu-box, .search-box {
      width:20%;
      display:none;
    }

    .menu-box {
      background-color:red;
    }

    .search-box {
      background-color:green;
    }

JAVASCRIPT

$('.menu').click(function(){
    $('.menu-box').slideToggle();
});

$('.search').click(function(){
    $('.search-box').slideToggle();
});

You can see a working demo here...

http://codepen.io/seraphzz/pen/zbHDk

I have had a look around for help, but all the solutions are found are for tabs, where one div is always showing. This is not what I am after. A div should only be showing if that link was clicked on.

So to confirm, if the 'menu' div is already open, and the user clicks on 'search', I want the 'menu' div to hide and the 'search' to show. The two divs should never be showing at the same time!

Thanks in advance


回答1:


Using the same class makes this a lot easier ?

<div class="btn">MENU</div>
<div class="btn">SEARCH</div>


<div class="slide menu-box">MENU BOX</div>
<div class="slide search-box">SEARCH BOX</div>

js

$('.btn').on('click', function(){
    $('.slide').slideUp().eq($(this).index()).stop().slideToggle();
});

FIDDLE




回答2:


Change your search click handler to be:

$('.search').click(function(){
    $('.search-box').slideToggle();

    if($(".menu-box").is(":visible")) {
        $(this).slideToggle();
    }

});

and your menu handler to do the same, only check for search-box visibility.




回答3:


<h3><a href="#1" class="toggler">Title of Section 1</a></h3>
<div id="1" class="element">Content goes here for the above h tag</div>

<h3><a href="#2" class="toggler">Title of Section 2</a></h3>
<div id="2" class="element">Content goes here for the above h tag</div>


$(".toggler").click(function(e) {
    e.preventDefault();
    var id = $(this).attr('href');

    $(".element").hide();
    $(id).show('slow');

});


来源:https://stackoverflow.com/questions/17000866/show-div-and-hide-existing-div-if-open-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!