简体   繁体   English

简单的jQuery手风琴切换

[英]Simple jQuery accordion toggle

I am working on a simple accordion with toggle states using jQuery. 我正在使用jQuery切换状态的简单手风琴。 So far so good, but when I click on a different toggle than the initial one that I've clicked on at the start it toggles itself, leaving the previous one with the opened state. 到目前为止,一切都很好,但是当我单击的开关与最初单击时所单击的开关不同时,它将自动进行开关,而前一个开关处于打开状态。

How can one do some kind of a check-up to see if there is another one opened and toggle its state as well? 如何进行某种检查以查看是否打开了另一个检查并同时切换其状态?

Here is a Fiddle. 这是小提琴。 Just mess around with it for a few seconds and you will understand what I mean. 随便摆弄几秒钟,您就会明白我的意思。

// Accordion init
// Hide accordion content on load
$('.accordion-content').hide();
$('.widget-accordion').find('.accordion-toggle').click(function() {

  // State change visuals
  $(this).toggleClass('opened');

  //Expand or collapse this panel
 $(this).next().slideToggle('fast');

  //Hide the other panels
  $(".accordion-content").not($(this).next()).slideUp('fast');

});

As stated in my comment above, here a working fiddle. 正如我在上面的评论中所述,这里是一个工作的小提琴。

The problem is that when you open one accordion item there is no other opened allowed which means that you have to clear every class which stands for the status open... 问题是,当您打开一个手风琴项目时,不允许打开其他项目,这意味着您必须清除代表打开状态的每个类。

Working Fiddle 工作小提琴

// Accordion init
// Hide accordion content on load
$('.accordion-content').hide();
$('.widget-accordion').find('.accordion-toggle').click(function() {
    $('.accordion-toggle').not(this).each(function(){
    $(this).removeClass("opened");
  });
  // State change visuals
  $(this).toggleClass('opened');

  //Expand or collapse this panel
  $(this).next().slideToggle('fast');

  //Hide the other panels
  $(".accordion-content").not($(this).next()).slideUp('fast');

});

Use This instead of toggleClass : 使用This而不是toggleClass

// State change visuals
 $('.accordion-toggle').removeClass('opened');
 $(this).addClass('opened');

Fiddle: https://jsfiddle.net/cndnnww5/5/ 小提琴: https : //jsfiddle.net/cndnnww5/5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM