LoginSignup
26
39

More than 3 years have passed since last update.

【JavaScript】タブの切り替え表示を実装する【JQuery】

Posted at

はじめに

webサイトでよく見るタブの切り替えを、JavaScriptを使って実装する方法を解説します。
あまり難しいことはないので順番に見ていきましょう!

先に今回のサンプルの完成イメージを載せておきます。
3d9f2899143344eb9d1a27b1c14f7420.gif

htmlファイル

タブとそれぞれのタブに対応した中身を用意します。
一つ目のタブ(tab)にactiveクラスをつけ、タブの中身(content)の一つ目にshowクラスをつけておきます。

htmlファイル
<div class="tab-area">
  <div class="tab active">
    タブ1
  </div>
  <div class="tab">
    タブ2
  </div>
  <div class="tab">
    タブ3
  </div>
  <div class="tab">
    タブ4
  </div>
  <div class="tab">
    タブ5
  </div>
</div>
<div class="content-area">
  <div class="content show">
    タブ1の中身です
  </div>
  <div class="content">
    タブ2の中身です
  </div>
  <div class="content">
    タブ3の中身です
  </div>
  <div class="content">
    タブ4の中身です
  </div>
  <div class="content">
    タブ5の中身です
  </div>
</div>

cssファイル

scssで書いてます。
タブのactiveとそれ以外、中身のshowとそれ以外がどのように表示されたら良いか書けばOKです。

scssファイル
.tab-area {
  display: flex;
  justify-content: space-around;
  background-color: #222e3e;
  cursor: pointer;
  .tab {
    width: 300px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    color: white;
    border-right: 1px solid #50637b;
    border-left: 1px solid #222e3e;
  }
  .tab.active {
    background-color: #ccc;
    color: #222e3e;
    border: none;
  }
}
.content-area {
  font-size: 30px;
  text-align: center;
  .content {
    display: none;
  }
  .content.show {
    margin-top: 50px;
    display: block;
  }
}

jsファイル

JQueryを使って書いてます。

jsファイル
$(function() {
  let tabs = $(".tab"); // tabのクラスを全て取得し、変数tabsに配列で定義
  $(".tab").on("click", function() { // tabをクリックしたらイベント発火
    $(".active").removeClass("active"); // activeクラスを消す
    $(this).addClass("active"); // クリックした箇所にactiveクラスを追加
    const index = tabs.index(this); // クリックした箇所がタブの何番目か判定し、定数indexとして定義
    $(".content").removeClass("show").eq(index).addClass("show"); // showクラスを消して、contentクラスのindex番目にshowクラスを追加
  })
})

最後に

クリックした箇所のクラス名をJavaScriptを使って変更していくだけなので、難しいことは特になかったかと思います。

タブを使った表示ができるとモダンな感じになるので積極的に使っていきましょう!

26
39
1

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
26
39