0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JS】アコーディオンメニューの様なQandA【jQuery】

Posted at

きっかけ

アコーディオンメニューの様なQandAを作ってと言われた

下準備

省略してbodyだけ書きます!

<body>
  <div class="qa-wrapper">
    <!-- ↓のdivをクリックすると開閉して欲しい -->
    <div class="qa-wrapper__qa">
      <div class="qa-wrapper__q">
        <p class="qa-wrapper__text">質問</p>
        <!-- ↓のdivの擬似要素をactiveクラスを追加して変更したい -->
        <div class="qa-wrapper__qButton"></div>
      </div>
      <!-- ↓のdivを展開格納したい -->
      <div class="a" style="display: none;">
        <p>回答</p>
      </div>
    </div>
  </div>
</body>
.qa-wrapper {
  &__q {
    /* 無駄に体裁… */
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
  }

  &__qButton {
    /* プラスマイナス表示 */
    position: relative;
    min-width: 20px;
    min-height: 20px;

    &::before {
      /* 横棒 */
      content: '';
      position: absolute;
      left: 0;
      top: 9px;
      min-width: 20px;
      min-height: 2px;
      background: #333;
    }

    &::after {
      /* 縦棒 */
      content: '';
      position: absolute;
      left: 9px;
      top: 0;
      min-width: 2px;
      min-height: 20px;
      background: #333;
    }

    &.active::after {
      /* 展開されたら非表示 */
      display: none;
    }
  }
}

よくあるjQuery

$(function () {
  $('.hoge').click($(function () {
    // hogeクラスにactiveクラスを追加?
    $(this).toggleClass('active');
    // fugaクラスをスライドして開閉
    $(this).next('.fuga').slideToggle();
  });
});

しかしこのまま転用すると、hogeクラスでしかfugaクラスが開閉できない。
僕の望んだ動きをしてくれない。

検索

検索してみると、親子関係で開閉させるには.find()を使うみたいです。

実装

$(function () {
  $('.qa-wrapper__qa').click(function () {
    $(this).find('.qa-wrapper__qButton').toggleClass('active');
    $(this).find('.a').slideToggle();
  });
});

これで指定した要素内のどこをクリックしても開閉できる。
やったー!

最後に

何度も忘れてしまっているのが…。
cssの適用
jsとjQueryの読み込み

コイツらを忘れて何度もリロードしてしまいました。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?