本文介绍了jQuery显示一个Div并隐藏其他的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有以下代码:

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");

});
});

我有多个<div>,我的想法是,当我打开<div>时,它会切换另一个<div>.然后,当我单击另一个<div>时,它会隐藏打开的<div>.因此,一次只能打开一个<div>.

I have multiple <div>'s, and my idea is that when 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.

我唯一的问题是使用此代码,当我尝试关闭已经打开的<div>时,它将关闭然后再次打开.因此,一个<div>将始终处于打开状态.

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.

我在下面添加了HTML和CSS.一切正常,除了我无法获得所有关闭状态.

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

我用包装纸将其中的5个相互堆叠.

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;}

推荐答案

这将解决该问题: http://jsfiddle.net/yrM3H/3/

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

您必须使用 .not() 从".active"部分中排除点击的元素点击的元素是".active".

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

这篇关于jQuery显示一个Div并隐藏其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:20