LoginSignup
0
1

More than 3 years have passed since last update.

【簡単にできる】jQueryでのタブ切り替え

Posted at

今回、jQueryによるタブの切り替えの方法について、備忘録的に記載していきます。

HTML

まずは、表示させるHTML部分のコードです。
タブ部分のul要素と表示するコンテンツ部分のul要素の2つを作成します。

qiita.html
<ul class="tabs">
    <li class="active">タブ1</li>
    <li>タブ2</li>
    <li>タブ3</li>
    <li>タブ4</li>
</ul>
<ul class="contents">
    <li class="active">サッカー</li>
    <li>バスケ</li>
    <li>野球</li>
    <li>バレー</li>
</ul>

CSS

次はCSSの記述です。
タブ部はactiveクラスが付与されているタブのみ色を変化させます。
またコンテンツ部は非表示にし、activeクラスが付与されている要素のみを表示する仕様です。

qiita.css
.tabs{overflow:hidden;}
.tabs li{background:#ccc; padding:5px 25px; float:left; margin-right:1px;}
.tabs li.active{background:#eee;}
.contents li{display:none;}
.contents .active {padding:20px; display:block;}
ul { list-style: none;}

jQuery

最後にjQueryの記述です。
クリックされたタブに対して、タブ部とコンテンツ部の両方にactiveを付与します。

qiita.js
$('.tab li').click(function() {
    var index = $('.tabs li').index(this);
    $('.contents li').removeClass('active');
    $('.contents li').eq(index).addClass('active');
    $('.tabs li').removeClass('active');
    $(this).addClass('active')
});

今回は、index()メソッドを用いて何番目のタブがクリックされたかを判別し、
その番号と同じ順番にあるコンテンツ部の要素にactiveを付与する処理にしました。

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