← 動的パーツギャラリーへ戻る

パーツ番号 03-01-09 ・ JavaScript使用

タブバー+スライドインジケータ

クリックしたタブへ下線が滑らかにスライド移動します。WordPressの投稿一覧のカテゴリ切替UIなどに応用できます。

clickjs

プレビュー

ソースコード

HTML

<div class="d03-01-09-wrap">
          <nav class="d03-01-09-tabs">
            <button type="button" class="active">ホーム</button>
            <button type="button">サービス</button>
            <button type="button">実績</button>
            <button type="button">会社概要</button>
            <span class="d03-01-09-line"></span>
          </nav>
          <p class="d03-01-09-hint">タブをクリックすると下線が移動します</p>
        </div>

CSS

.d03-01-09-wrap{width:100%;max-width:340px}
        .d03-01-09-tabs{
          position:relative;display:flex;
          border-bottom:2px solid #e2e8f0;
        }
        .d03-01-09-tabs button{
          flex:1;border:none;background:transparent;cursor:pointer;
          font-size:13px;font-weight:600;color:#64748b;
          padding:12px 4px;transition:color .3s ease;
          font-family:inherit;
        }
        .d03-01-09-tabs button:hover{color:#1d4ed8}
        .d03-01-09-tabs button.active{color:#2563eb}
        .d03-01-09-line{
          position:absolute;bottom:-2px;left:0;height:2px;
          background:#2563eb;border-radius:2px;
          transition:left .35s cubic-bezier(.4,0,.2,1),width .35s cubic-bezier(.4,0,.2,1);
        }
        .d03-01-09-hint{margin:14px 0 0;font-size:11px;color:#94a3b8;text-align:center}

JavaScript

(function(){
        var tabs=document.querySelector('.d03-01-09-tabs');
        if(!tabs)return;
        var line=tabs.querySelector('.d03-01-09-line');
        function move(btn){
          line.style.left=btn.offsetLeft+'px';
          line.style.width=btn.offsetWidth+'px';
        }
        tabs.querySelectorAll('button').forEach(function(b){
          b.addEventListener('click',function(){
            tabs.querySelector('button.active').classList.remove('active');
            b.classList.add('active');
            move(b);
          });
        });
        function init(){move(tabs.querySelector('button.active'))}
        if(document.readyState==='complete'){init()}
        else{window.addEventListener('load',init)}
      })();

クラス名 .d03-01-09 は本ライブラリ内での識別用です。複数のパーツを同じページで使う場合は、重複しないよう名前を変更してください。