LoginSignup
2
2

More than 5 years have passed since last update.

【jQuery】classの付け外しによるアコーディオン作成

Posted at

以下のような、質問を押下するとその質問の答えだけ表示されるようなアコーディオンをjQueryを使って作ります。
https://shintaro-hirose.github.io/test_-02/

まずはhtmlを記述します。

index.html
    <div id="faq">
        <div class="faq-item">
            <div class="question">
                <p class>質問1</p>
                <span>+</span>
            </div>
            <p class="answer">答え1</p>
        </div>
        <div class="faq-item">
            <div class="question">
                <p class>質問2</p>
                <span>+</span>
            </div>
            <p class="answer">答え2</p>
        </div>
        <div class="faq-item">
            <div class="question">
                <p class>質問3</p>
                <span>+</span>
            </div>
            <p class="answer">答え3</p>
        </div>
    </div>

faq-itemが3つ並列しており、その中で+マークをspanで貼り付けています。

さて、ここからjsやcssをいじっていきましょう。

デフォルトで答えを非表示にする

style.css
.answer{
    display:none;
}

jQueryを実装する

script.js
$(function(){
    $('.faq-item').click(function(){
        var $answer = $(this).find('.answer');
        if ($answer.hasClass('open')){
            $answer.removeClass('open');
            $answer.slideUp();
            $(this).find('span').text('+');
        } else {
            $answer.addClass('open');
            $answer.slideDown();
            $(this).find('span').text('-');
        }
    });
});

手順としては、
faq-itemをクリックしたときに...

 クリックしたitemの答えを変数answerに入れる

 もしanswerにクラスopenが含まれていたら...
  answerからクラスopenを取り除く
  答えを非表示にする
  spanの中身を書き換える

 もしanswerにクラスopenが含まれていなければ...
  answerにクラスopenを追加する
  答えを表示する
  spanの中身を書き換える

以上で、アコーディオンをつくることができました。
今回書いたプログラムはこちら↓
https://github.com/shintaro-hirose/test_-02

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2