Traversingメソッドを利用
Traversingのメリット
トラバースを利用することで、イベントが発生した要素に関連した要素を操作する事ができます。ボタンが複数ある場合などは「this」を使う事になりますが、このトラバースを使えば操作したい要素を「this」から見てどういう関係性にある「要素」、という形で指定する事ができます。jQueryを使う上で非常に大事な考え方なので、しっかりと理解しましょう。
childrenメソッド
jQueryオブジェクトで指定した要素の「子」要素でセレクタにマッチする要素を選択します。子要素とは階層構造(入れ子構造)において直下にある要素のことです。
childrenメソッドを利用すれば「セレクタ:>(子要素)」と同じようなことが可能です。
parentメソッド
指定した要素の「親」要素を選択します。親要素とは階層構造(入れ子構造)において直上にある要素のことです。
名前が似ているparentsメソッドはparentメソッドと異なり「先祖」要素も選択します。
siblingsメソッド
指定した要素の兄弟要素(同じ階層の要素)を選択します。引数を設定しない場合はすべての兄弟要素を選択します。
作例
index.html
<ul id="tab"> <li class="current"><a href="#step1">ステップ<span>1</span></a></li> <li><a href="#step2">ステップ<span>2</span></a></li> <li><a href="#step3">ステップ<span>3</span></a></li> </ul> <div class="box current" id="step1"> <h2>ステップ1の詳細</h2> <p>この文章はダミーです。文字の大きさ、量、字間、行間等を確認するために入れています。</p> <p><a href="#"><img src="img/nathan-fertig-FBXuXp57eM0-unsplash.jpg" alt=""></a></p> </div> <div class="box" id="step2"> <h2>ステップ2の詳細</h2> <p>この文章はダミーです。文字の大きさ、量、字間、行間等を確認するために入れています。</p> <p><a href="#"><img src="img/phillip-goldsberry-fZuleEfeA1Q-unsplash.jpg" alt=""></a></p> </div> <div class="box" id="step3"> <h2>ステップ3の詳細</h2> <p>この文章はダミーです。文字の大きさ、量、字間、行間等を確認するために入れています。</p> <p><a href="#"><img src="img/toa-heftiba-FV3GConVSss-unsplash.jpg" alt=""></a></p> </div> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script> <script> $(function(){ $('#tab a').on('click',function(){ $(this).parent('li').addClass('current').siblings('li').removeClass('current'); var target=$(this).attr('href'); $(target).fadeIn(500).siblings('.box').hide(); }); }); </script>
style.css
#tab{ width: 500px; margin: 50px auto; display: flex; justify-content: space-between; position: relative; } #tab::after{ display: block; content: ""; width: 100%; height: 4px; background-color: #555; position: absolute; top: 0; bottom: 0; margin: auto; z-index: -2; } #tab>li{ width: 100px; height: 100px; border-radius: 50%; background-color: #FFF; border: 4px solid #555; } #tab a{ display: block; color: #555; text-align: center; height: 100%; padding-top: 16px; line-height: 1.2; } #tab span{ display: block; font-weight: bold; font-size: 32px; } #tab>li.current{ background-color: #555; position: relative; } #tab>li.current::after{ display: block; content: ""; width: 130%; height: 130%; border-radius: 50%; background-color: #FFF; position: absolute; top: 0; right: 0; bottom: 0; left: -15%; margin: auto; z-index: -1; border: 4px solid #555; } #tab>li.current>a{ color: #FFF; } #tab>li.current span{ font-size: 38px; } .box{ width: 600px; border: 2px solid #333; margin: 0 auto; padding: 20px; display: none; } .box.current{ display: block; } .box>p{ margin-bottom: 10px; } img{ max-width: 100%; }