[jQuery] クリックでセクションの表示・非表示を切り替える
目次みたいなリンク一覧がって、リンクをクリックをすると、そのセクション(ブロック)だけが表示され、クリックするたびにセクションが切り替わるような画面を作ったのでメモ。
アプリ名一覧みたいなのがあって、アプリ名をクリックすると、そのアプリの紹介だけが表示されるようなやつ。
一覧が、リンクの場合と、ボタンの場合の 2 種類を作った。
リンクの場合は、 href の値と id で表示・非表示を切り替える。
ボタンの場合は、 id と class 名を使って切り替える。
セクションの切り替えは、
hide() で非表示
show() で表示、または
toggle() で表示(クリックするごとに表示・非表示を繰り返す)
表示・非表示のメソッドは、 fadeIn() / fadeOut() や slideDown() / slideUp() などアニメーション付きのもあるので、それらを使ってもいい。
リンクで切り替え
デモ
See the Pen section show/hide with link on Divi by AgoPeanuts (@AgoPeanuts) on CodePen.
HTML
<!-- List部分 -->
<div class="et_pb_module">
<a href="#fuu" class='secList'>Section1</a>
</div>
<div class="et_pb_module">
<a href="#euu" class='secList'>Section2</a>
</div>
<div class="et_pb_module">
<a href="#guu" class='secList'>Section3</a>
</div>
<!-- Sections -->
<div id="fuu" class="section">
<h2>Section1</h2>
<p>hoge1</p>
</div>
<div id="euu" class="section">
<h2>Section2</h2>
<p>hoge2</p>
</div>
<div id="guu" class="section">
<h2>Section3</h2>
<p>hoge3</p>
</div>
a タグの href の値と、表示・非表示を切り替えるセクション (ここでは div )の id を同じにする。
セクション部分を作るタグは、 section タグとかでもいい。
各 a タグには同じクラス名をつけ、各セクションにもセクション用の同じクラス名をつける。
jQuery
$(function(){
$('.section').hide();
$('.secList').on('click',function(){
$('.section').not($($(this).attr('href'))).hide();
// フェードイン・アウトのアニメーション付で、表示・非表示を交互に実行する
$($(this).attr('href')).fadeToggle(1000);
// show を使うと、表示するだけ ( 同じボタンを何回押しても変わらない )
// $($(this).attr('href')).show();
});
});
$('.section').hide(); で初期表示時は、セクションは全部非表示にする。
$('.section').not($($(this).attr('href'))).hide(); について、$(this).attr('href') で取得できるのは a タグの href の値 ( #euu とか)。.not を使ってクリックされた href の値と等しくない
id の要素を取得し、非表示にしている。
ボタンで切り替え
デモ
See the Pen section show/hide by AgoPeanuts (@AgoPeanuts) on CodePen.
HTML
<!-- List -->
<div class="et_pb_module">
<button id="fuu" class='secList'>Section1</button>
</div>
<div class="et_pb_module">
<button id="euu" class='secList'>Section2</button>
</div>
<div class="et_pb_module">
<button id="guu" class='secList'>Section3</button>
</div>
<!-- Sections -->
<div class="fuu section">
<h2>Section1</h2>
<p>hoge1</p>
</div>
<div class="euu section">
<h2>Section2</h2>
<p>hoge2</p>
</div>
<div class="guu section">
<h2>Section3</h2>
<p>hoge3</p>
</div>
各ボタンには同じクラス名をつけ、各セクションにもセクション用の同じクラス名をつける。
ボタンの id と同じ値を、対応するセクションのクラスにつける。
jQuery
$(function(){
$('.section').hide();
$('.secList').on('click',function(){
// クリックした要素の ID と違うクラス名のセクションを非表示
$('.section').not($('.'+$(this).attr('id'))).hide();
// クリックした要素の ID と同じクラスのセクションを表示
$('.'+$(this).attr('id')).show();
// toggle にすると、同じボタンを 2 回押すと非表示になる
// $('.'+$(this).attr('id')).toggle();
});
});
$(this).attr('id') でクリックしたボタンの id を取得。
セクションはボタン id と同じクラス名になっているので、 '.' をつける。