Chapter.6JavaScript(jQuery)基礎

05アコーディオン(開閉)を作成する

ここにテキストが入ります。

ここにテキストが入ります。

ここにテキストが入ります。

ここにテキストが入ります。

ここにテキストが入ります。

ここにテキストが入ります。

ここにテキストが入ります。

ここにテキストが入ります。

イベント発生させる上の要素(と操作したい要素)のID名 #chapter6-5-btn
イベント発生させる下の要素(と操作したい要素)のID名 #chapter6-5-btn2
アコーディオンで開く要素のClass名 .txt
追加または削除するクラス名 .active

-- js --
$(function(){
  $('#chapter6-5-btn').click(function(){
    $(this).toggleClass('active').next().toggle();
  });
  $('#chapter6-5-btn2').click(function(){
    $(this).toggleClass('active').next().slideToggle();
  });
});

-- css --
.group {
  position: relative;
  width: 400px;
  height: 100px;
  margin: 0 auto;
  background: #ddd;
}
.group::before {
  content: "";
  position: absolute;
  top: 50%;
  right: 20px;
  width: 10px;
  height: 10px;
  margin-top: -4px;
  border-bottom: 2px solid #000;
  border-left: 2px solid #000;
  transform: rotate(-45deg) translateY(-50%);
}
.group.active::before {
  margin-top: 1px;
  border-bottom: none;
  border-left: none;
  border-top: 2px solid #000;
  border-right: 2px solid #000;
}
.txt {
  display: none;
  width: 400px;
  margin: 0 auto;
  padding: 20px;
  background: #eee;
}