如果使用jQuery打开,是否显示div并隐藏现有的div? [英] show div and hide existing div if open with jQuery?

查看:77
本文介绍了如果使用jQuery打开,是否显示div并隐藏现有的div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个默认情况下隐藏的div.然后,用户在点击时显示div.如果一个div已经打开,并且用户单击以显示另一个div,则我希望当前的div隐藏,并显示新的div.

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.

我当前的代码是这个.

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

我四处寻找帮助,但是找到的所有解决方案都是针对选项卡的,其中始终显示一个div.这不是我所追求的.仅当单击该链接时才显示div.

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.

因此,请确认一下,如果菜单" div已经打开,并且用户单击搜索",我希望隐藏菜单" div,并显示搜索".两个div永远不应同时显示!

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!

预先感谢

推荐答案

使用相同的类会让这变得容易吗?

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

这篇关于如果使用jQuery打开,是否显示div并隐藏现有的div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆