LoginSignup
29
40

More than 5 years have passed since last update.

jQueryとCSSでシンプルなタブ切り替え

Last updated at Posted at 2017-08-06

jQueryとCSSでシンプルなタブ切り替え

条件

・カレント表示もできるタブ切り替え
・なるべくシンプルな記述
・html構造や装飾が変わっても使いまわせる

HTML

html
<div class="ChangeElem_Btn_Content">
  <button class="ChangeElem_Btn">1番目のタブ</button>
  <button class="ChangeElem_Btn">2番目のタブ</button>
  <button class="ChangeElem_Btn">3番目のタブ</button>
</div>
<ul>
  <li class="ChangeElem_Panel">1番目のコンテンツ</li>
  <li class="ChangeElem_Panel">2番目のコンテンツ</li>
  <li class="ChangeElem_Panel">3番目のコンテンツ3</li>
</ul>

[補足]
・タブに class="ChangeElem_Btn" を、中身に ' class="ChangeElem_Panel" を付与します。
・何番目のタブをクリックしたら何番目の要素を表示という考え方なので、タブも中身もちゃんと上から順番に並べます。
ChangeElem_Btn_Contentは装飾と可読性の関係で残しています。 無くても機能上支障はありません。html構造についてもbtnでなくてもulでなくても大丈夫です。

CSS

タブの中身を初期非表示

css
.ChangeElem_Panel{
  display: none;
}

[補足]
・タブの中身を一旦隠しています。
・これをベースに使い回す前提のため、タブ自体の装飾は割愛しています。初期1番目のタブとカレントタブに is-active クラスがつきますので、 is-active クラスの有無でカレントと通常時のタブの装飾を切り替えています。
→サンプルはこちら

jQuery

jQuery
$(function () {
  /*初期表示*/
  $('.ChangeElem_Panel').hide();
  $('.ChangeElem_Panel').eq(0).show();
  $('.ChangeElem_Btn').eq(0).addClass('is-active');
  /*クリックイベント*/
  $('.ChangeElem_Btn').each(function () {
    $(this).on('click', function () {
      var index = $('.ChangeElem_Btn').index(this);
      $('.ChangeElem_Btn').removeClass('is-active');
      $(this).addClass('is-active');
      $('.ChangeElem_Panel').hide();
      $('.ChangeElem_Panel').eq(index).show();
    });
  });
});

最後に

とにかくシンプル。かつ、html構造や装飾が変わってもささっと使いまわせるように作ってます。
→サンプルはこちら

29
40
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
29
40