我正在用简单的js创建手风琴菜单。如何在点击打开/关闭时添加和删除活动类?
<div class="mobile-categories">
<h4 class="mcategory-toggle">Vehicles</h4>
<ul class="msub-categories">
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
<h4 class="mcategory-toggle">Education</h4>
<ul class="msub-categories">
<li>Option 10</li>
<li>Option 20</li>
<li>Option 30</li>
</ul>
<h4 class="mcategory-toggle">Shops</h4>
<ul class="msub-categories">
<li>Option 14</li>
<li>Option 25</li>
<li>Option 36</li>
</ul>
</div>
答案 0 :(得分:2)
您可以使用toggleClass方法。
$(document).ready(function($) {
$('.mobile-categories').find('.mcategory-toggle').click(function(){
var self = $(this);
//Expand or collapse this panel
self.next().slideToggle('fast');
//Remove active class for all element, except the current selected item
$('.mcategory-toggle').not(self).removeClass('active');
//Toggle active class for the current element
self.toggleClass('active');
//Hide the other panels
$(".msub-categories").not(self.next()).slideUp('fast');
});
});
您可以看到Working Fiddle
答案 1 :(得分:0)
将jQuery切换类方法添加到您的点击功能:
$(this).toggleClass('active');
答案 2 :(得分:0)
在使用jQuery单击时添加删除类
$(document).ready(function(){
$('.btn').on('click',function(){
if($('.box').hasClass('current')){
$('.box').removeClass('current');
}else{
$('.box').addClass('current');
}
});
});