[英]Toggle class on child elements (and remove siblings)
我有以下代碼,用於通過切換.active
類來創建手風琴效果。 單擊.section-header
,我在header和.section-content
上切換一個類。 這運作良好。
但是,如上所述,這是為了創建手風琴效果,該效果由多個.accordion .accordion-section
<div>
標簽修飾而成。 我需要調整jquery,以便從每個.active
.accordion-section
刪除所有.active
類,而不是當前處於活動狀態的類。 目前,單擊.section-header
會在所有.section-content
<div>
標記上切換一個.active
類。
謝謝。
的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');
});
$('.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');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.