我有以下代码,用于通过切换.active
类来创建手风琴效果。点击.section-header
后,我在标题和.section-content
上切换了一个类。这很有效。
然而,如上所述,这是为了创建一个手风琴效果,它是多个.accordion-section
<div>
标签。我需要调整jquery,以便除了当前活动的.active
之外的所有.accordion-section
类。目前,点击.section-header
可在所有.active
.section-content
个标签上切换<div>
课程。
感谢。
HTML
<div class="accordion-section">
<a class="section-header">
<h3>Title</h3>
</a>
<div class="section-content">
<div>Content</div>
</div>
</div>
JS
$('.accordion-section .section-header').click(function(){
$(this).toggleClass('active');
$(this).siblings().toggleClass('active');
});
答案 0 :(得分:1)
$('.accordion-section .section-header').click(function(){
// Check to see the initial state of the element
var isActive = $(this).hasClass('active');
// first remove the active class from all other section headers within this accordion section
$('.accordion-section')
.find('.section-header, .section-content')
.removeClass('active');
// Get the header and content for this section
var sectionHeaderAndContent = $(this)
.closest('.accordion-section')
.find('.section-header, .section-content');
// Toggle Active State: Set final active state based on state when clicked
(isActive) ? sectionHeaderAndContent.removeClass('active'): sectionHeaderAndContent.addClass('active');
});