超级简单的手风琴菜单,带有打开/关闭图标

时间:2016-07-22 08:32:52

标签: jquery accordion

我使用简单的手风琴,效果很好,唯一的需要是显示开/关图标。不知道如何将类添加/删除到将与手风琴状态交互的父项,所以需要你的帮助。

<!-- JS -->
<script type="text/javascript">
$(document).ready(function($) {
$('#accordion').find('.accordion-toggle').click(function(){

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

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

});
});
</script>

<!-- CSS -->
<style>
.accordion-toggle {cursor: pointer;}
.accordion-content {display: none;}
.accordion-content.default {display: block;}
</style>

<!-- HTML -->
<div id="accordion">
<h4 class="accordion-toggle">Accordion 1</h4>
<div class="accordion-content default">
<p>Cras malesuada ultrices augue molestie risus.</p>
</div>
<h4 class="accordion-toggle">Accordion 2</h4>
<div class="accordion-content">
<p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
</div>
<h4 class="accordion-toggle">Accordion 3</h4>
<div class="accordion-content">
<p>Vivamus facilisisnibh scelerisque laoreet.</p>
</div>
</div>

1 个答案:

答案 0 :(得分:0)

你提到隐藏/显示图标,但最后,你真的想要一个关于如何:

的指南
  

&#34;将类添加/删除到将与accordion交互的父项   状态&#34;

因此,我假设您打算使用课程来互换地展示一个“倒塌”的课程。并且&#39;扩展&#39;单击的父项目的图标。

编辑:根据您的澄清,我修改了代码。请参阅下面的示例代码:

&#13;
&#13;
$(document).ready(function($) {

//adds the "collapsed" class to each parent
$('#accordion .accordion-toggle').addClass('collapsed'); 

$('#accordion').find('.accordion-toggle').click(function(){
  //Expand or collapse this panel
  $(this).next().slideToggle('fast');
  
  //toggles between collapsed and expanded classes
$(this).toggleClass('collapsed expanded');
  
  //removes any instance of "expanded" from the other parents and replace it with the "collapsed" class
     $("#accordion .accordion-toggle").not($(this)).removeClass('expanded').addClass('collapsed');
  
  //Hide the other panels
  $(".accordion-content").not($(this).next()).slideUp('fast');  

});
});
&#13;
.expanded {
  background:red;
}

.collapsed {
  background:blue;
}
.accordion-content:not(.default) {
  display:none;
}
h4 {
  cursor:pointer;
}
/* the css below is unnecessary for the accordion, but just to prevent the vertical scrollbars from showing up using stackoverflow's code screen */ 
body {
  overflow:hidden;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="accordion">
<h4 class="accordion-toggle">Accordion 1</h4>
<div class="accordion-content default">
<p>Cras malesuada ultrices augue molestie risus.</p>
</div>
<h4 class="accordion-toggle">Accordion 2</h4>
<div class="accordion-content">
<p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
</div>
<h4 class="accordion-toggle">Accordion 3</h4>
<div class="accordion-content">
<p>Vivamus facilisisnibh scelerisque laoreet.</p>
</div>
</div>
&#13;
&#13;
&#13;