开发者

jQuery Show One Div and Hide the Others

开发者 https://www.devze.com 2023-03-23 12:32 出处:网络
http://jsfiddle.net/yrM3H/2/ I have the following code: jQuery(document).ready(function() { jQuery(\".toggle\").next(\".hidden\").hide();

http://jsfiddle.net/yrM3H/2/

I have the following code:

jQuery(document).ready(function() {
  jQuery(".toggle").next(".hidden").hide();
  jQuery(".toggle").click(function()
  { 
    $('.active').toggleClass('active').next('.hidden').slideToggle(300);
    $(this).toggleClass('active').next().slideToggle("fast");   

});
});

I have multiple <div>'s, and my idea is that wh开发者_开发技巧en I open a <div> it toggles another <div>. And then, when I click another <div>, it hides the open <div>. Therefore only one <div> is open at a time.

My only issue is that with this code, when I try to close a <div> that is already open, it will close and then open again. Thus one <div> will always be open.

Any help will be appreciated, thank you.

I added the HTML and CSS below. Everything works fine, except that I cannot get it so that all of them are closed.

I have 5 of these stacked on each other in a wrapper.

*edited for clarity *

// HTML
<div class="toggle"></div>
<div  class="hidden"></div>

// CSS
.toggle {width:398px; height:48px; cursor: pointer;}
.hidden {width:300px; height:75px; background-color:#333333; margin-left:50px; text-indent:25px;}


This will fix it: http://jsfiddle.net/yrM3H/3/

  jQuery(".toggle").click(function()
  { 
    $('.active').not(this).toggleClass('active').next('.hidden').slideToggle(300);
    $(this).toggleClass('active').next().slideToggle("fast");   
  });

you have to exclude the clicked element form your ".active" section using .not() since the clicked element is ".active" to.

0

精彩评论

暂无评论...
验证码 换一张
取 消