问题
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