タブを切り替えて、表示させるコンテンツを変えたい
こんな感じのタブをクリックするとそれに応じた、文章とか画像が表示されるやつ。

今回はタブアニメーションの実装方法をご紹介します。
コード
こちらが実際のコードと挙動です。
タブをクリックすると、それに応じた画像が表示されます。
See the Pen タブjs by YT (@YT-the-scripter) on CodePen.
<div class='tab'>
    <div class='tab__buttons'>
      <button class="tab__button js-tab-button is-active">タブ1</button>
      <button class="tab__button js-tab-button">タブ2</button>
      <button class="tab__button js-tab-button">タブ3</button>
    </div>
    <div class='tab__contents'>
      <div class="tab__item is-active js-tab-item">
        <img src="https://~~" />
      </div>
      <div class="tab__item js-tab-item">        
        <img src="https://~~" />
      </div>
      <div class="tab__item js-tab-item">        
        <img src="https://~~" />
      </div>
    </div>
  </div>
  </div>
まずポイントは、初期状態で表示させるtab__buttonと、tab__itemに”is-active”クラスを付与していること。
これで画面表示時に、必ず一つ目のタブがクリックされていて、一つ目の画像が表示されている挙動を表現できます。
body {
  width: 300px;
  margin: 0 auto;
}
.tab {
  margin-top: 50px;
  width: 100%;
}
.tab__buttons {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}
.tab__button {
  width: 33%;
  cursor: pointer;
}
.tab__contents {
  margin-top: 20px;
}
.tab__item {
  display: none;
}
.tab__item.is-active {
  display: block;
}
.tab__item img {
  aspect-ratio: 100 / 100;
  width: 100%;
ポイントは、.tab__itemの初期状態をdisplay-noneにして消していること。
is-activeが付与されている時にのみ、表示されるようにします。
そしてこのis-activeをjsでつけ外しすることで、タブアニメーションを実装します。
$(function () {
  // 該当するクラスを変数に格納する。→コード量の節約
  const tabButton = $(".js-tab-button"),
    tabItem = $(".js-tab-item");
  // tabButtonをクリックすると処理が発火する。
  tabButton.on("click", function () {
    // 並列で並んでる内の、何番目のtabButtonかを取得
    let index = tabButton.index(this);
    // tabButtonとtabItemに初期状態でついている、"is-active"を削除
    tabButton.removeClass("is-active");
    tabItem.removeClass("is-active");
    // 該当するindexのtabButtonとtabItemに"is-active"を付与
    tabButton.eq(index).addClass("is-active");
    tabItem.eq(index).addClass("is-active");
  });
});
①tabButtonをクリックすると、処理が発火
②クリックしたtabButtonが何番目かを取得
③tab__buttonとtab__itemに付与されている”is-active”を削除する。
④ ②で取得したindexに該当するtab__buttonとtab__itemに”is-active”を付与する
結果的に、クリックした要素にis-activeが付与されることで画像が切り替わるという仕組みです。
まとめ
以上、今回はタブアニメーションについてまとめました。
基本的には、is-activeを付け替える仕組みがわかれば実装できるかと思います。
			
			
			
			
			
コメント