首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >切换子元素的类(并删除兄弟姐妹)

问切换子元素的类(并删除兄弟姐妹)
EN

Stack Overflow用户
提问于 2017-04-26 20:22:46
回答 1查看 1.4K关注 0票数 0

我有下面的代码,通过切换.active类来创建手风琴效果。单击.section-header后,我将在标题和.section-content上切换一个类。效果很好。

但是,如前所述,这是为了创建一个手风琴效应,它是由多个.accordion-section <div>标记组成的。我需要调整jquery,以便从除当前活动的.accordion-section之外的每个.accordion-section中删除所有的jquery类。目前,单击.section-header在所有.section-content <div>标记上切换一个.active类。

谢谢。

代码语言:javascript
复制
<div class="accordion-section">
    <a class="section-header">
        <h3>Title</h3>
    </a>
    <div class="section-content">
        <div>Content</div>
    </div>
</div>

JS

代码语言:javascript
复制
$('.accordion-section .section-header').click(function(){
    $(this).toggleClass('active');
    $(this).siblings().toggleClass('active');
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-26 21:46:45

代码语言:javascript
复制
$('.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');
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43643850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档