在简单 jquery 手风琴中切换 css 样式

toggle css style in simple jquery accordian

我有一个用 Jquery 制作的简单手风琴。它在项目上切换打开和关闭,还关闭任何其他活动项目。

代码如下:

  $(document).ready(function($) {
    $('#accordion').find('.accordion-toggle').click(function(){

    $(this).toggleClass('activeState');

      // Remove active state from other panels not selected
      $("#accordian").not($(this)).removeClass('activeState');

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

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

    });
  });

现在我只是使用 'activeState' class 添加黄色的背景颜色(稍后我想使用图标 classes)。现在它在打开和关闭同一项目时可以很好地切换。但是我希望它在单击另一个手风琴项目时 toggle/remove activeState class (然后显然将 activeState class 附加到新打开的手风琴项目。我正在尝试使用“。 not()" jQuery 函数从任何不是被点击的活动对象的 '.accordian-toggle' 项目中删除 activeState class。我在这里是因为我运气不好有了它。

这是 JSFiddle https://jsfiddle.net/0LLncd4d/26/ 我可以就我可能忽略的地方寻求一些帮助吗?

替换这两行

$(this).toggleClass('activeState');
$("#accordian").not($(this)).removeClass('activeState');

$('.accordion-toggle').removeClass('activeState');
if($(this).parent().find('.accordion-content').css('display')=='none'){
   $(this).addClass('activeState');
}

这样试试:

 $(document).ready(function($) {
$('#accordion').find('.accordion-toggle').click(function(){

$(this).toggleClass('activeState');

  // Remove active state from other panels not selected
  $(".accordion-toggle").not($(this)).removeClass('activeState');

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

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

  });
 });