【问题标题】:jQuery Accordion misbehaving when expanding and contractingjQuery Accordion 在扩展和收缩时行为不端
【发布时间】:2014-02-07 12:38:03
【问题描述】:

我无法找出手风琴中的错误。单击时箭头图标行为异常。如果你去here,你会看到一些被手风琴隐藏的类别。当您单击一个然后关闭它时,它会正常运行。但是,如果您单击一个,然后在关闭第一个之前单击下面的另一个,您会注意到上面的箭头已返回到“关闭”位置而没有关闭它。

这是组成每个手风琴的 HTML:

<dl class="accordion">
<dt><strong>Accordion Title:</strong>&nbsp;&nbsp;Details</dt>
<dd>Hidden details</dd>
</dl>

箭头的 CSS:

.accordion dt:after {
  content: "\f125";
  color: #ED4F30;
  font-family: "Ionicons";
  padding-left: 10px;
}

.accordion dt.accordion-active:after {
  content: "\f123";
  color: #ED4F30;
  font-family: "Ionicons";
  padding-left: 10px;
}

最后是我用来展开/折叠的 jQuery:

function ($) {
  //Hide all panels
    var allPanels = $('.accordion > dd').hide();
  //Show first panel
  //$('.accordion > dd:first-of-type').show();
  //Add active class to first panel 
  //$('.accordion > dt:first-of-type').addClass('accordion-active');
  //Handle click function
    jQuery('.accordion > dt').on('click', function () {
      var $this = $(this) ,
          $target = $this.next();
           jQuery('.accordion > dt.accordion-active').not($this.toggleClass('accordion-active')).removeClass('accordion-active');
      $this.siblings('dd').not($target.addClass('active').slideToggle()).slideUp();
      return false;
    });
}

任何想法我错过了什么?

【问题讨论】:

  • not() 中带有 toggle() 的长行让这段代码难以理解。

标签: javascript jquery html accordion


【解决方案1】:

看起来你有点把事情复杂化了。你不需要使用“not()”方法来过滤掉任何东西。您只需在 2 个状态(添加/删除类、显示/隐藏元素)之间切换,因此您只需要使用 2 个 jQuery 方法,这些方法已经在您的代码中。

jQuery('.accordion > dt').on('click', function () {
    var $this = $(this),
        $target = $this.next();
    $this.toggleClass('accordion-active');
    $target.slideToggle();
    return false;
});

这是一个基于您提供的代码的 JSFiddle:http://jsfiddle.net/e5pe5/

让我知道这是否是您的手风琴的预期功能。

【讨论】:

  • 完美!谢谢@Inoogn,这正是我想要的。我正在修改某人的代码,但我过于复杂了。干杯:)
猜你喜欢
  • 2013-05-17
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
相关资源
最近更新 更多