みなさん、お久しぶりです。気が付けば最後の更新から1か月半。だいぶ更新してないと思い、こないだ仕事で実装したタブ切り替えメニューをご紹介します。
まずはDEMOから。
DEMO①
mainArea内のdivの中身はご自由にどうぞ。
HTML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="nav"> | |
<ul> | |
<li id="nav01">メニュー1</li> | |
<li id="nav02">メニュー2</li> | |
<li id="nav03">メニュー3</li> | |
<li id="nav04">メニュー4</li> | |
<li id="nav05">メニュー5</li> | |
</ul> | |
</div> | |
<div class="mainArea"> | |
<div id="tab01"></div> | |
<div id="tab02"></div> | |
<div id="tab03"></div> | |
<div id="tab04"></div> | |
<div id="tab05"></div> | |
</div> |
CSS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.nav ul{ | |
width: 100%; | |
font-size: 0; | |
} | |
.nav li{ | |
display: inline-block; | |
width: calc(100% / 5); | |
height: 80px; | |
border: 1px solid #666; | |
font-size: 1rem; | |
font-weight: bold; | |
text-align: center; | |
line-height: 80px; | |
cursor: pointer; | |
} | |
#tab01{background: gray} | |
#tab02{background: skyblue} | |
#tab03{background: yellow} | |
#tab04{background: lightgreen} | |
#tab05{background: orange} | |
.mainArea{ | |
position: relative; | |
width: 100%; | |
} | |
[id^="tab"]{ | |
display: none; | |
position: absolute; | |
top: 0; | |
left: 0; | |
width: 100%; | |
height: 500px; | |
} | |
#tab01{ | |
display: block; | |
position: static; | |
} |
jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('#nav01').addClass('current'); | |
for(i=1;i<=5;i++){ | |
tabIndex(i); | |
} | |
function tabIndex(index){ | |
$('#nav0'+index).on('click',function(){ | |
if(!$(this).hasClass('current')){ | |
$('[id^="nav"]').removeClass('current'); | |
$(this).addClass('current'); | |
$('[id^="tab"]:visible').fadeOut(1000); | |
$('#tab0'+index).fadeIn(1000); | |
} | |
}); | |
} |
○コード解説
メニューと下の表示エリアのid名の数字をいっしょにすることで、for文で操作しやすくしています。
表示しているメニューをクリックしてもフェードアニメーションが発生したので、currentというクラス名をつけて、条件分岐させています。slideとかにしてもおもしろい動きになるかも。
次回はドロップダウンメニューの予定。いつになることやら・・・。