ウェブデザインの中で、タブ切り替え機能はコンテンツを整理し、ユーザーにとってアクセスしやすくするための効果的な方法です。今回は、PCでのタブ切り替えとモバイルでのアンカーリンク機能を備えたinvisibleTab.jsの解説を行います。

コード

(function () {
//invisibleTab:CSS
var insertStyle = document.createElement('style');
insertStyle.insertAdjacentHTML('beforeend', `@charset "utf-8";
/* タブメニュー
-------------------------------------- */
.tab-container {
	position: relative;
	z-index: 10;
	display: block;
	width: 100%;
	max-width: 100%;
	height: auto;
	/* padding: 上  横  下 */
	padding: 1rem 0px 1rem;
	overflow: hidden;
}

.tab-container ul.menu {
	width: 1000px;
	max-width: 90vw;
	height: auto;
	margin-right: auto;
	margin-left: auto;
}

.tab-container ul.menu>

li {
	width: 100%;
	height: auto;
	text-align: center;
	margin-bottom: 5px;
}

.tab-container ul.menu>
li>

a {
	width: 100%;
	height: auto;
	padding: 0.2em 0px;
	font-family: 'Cinzel', serif;
	border: 1px solid #4F6874;
}

/* (PC) */
@media print,
screen and (min-width: 768px) {
	.tab-container ul.menu {
		/* Flex */
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.tab-container ul.menu>
	li:not(:first-of-type)>

	a {
		border-left: none;
	}
}

.tab-container ul.menu>
li.current_tab_item>

a {
	background: hsla(200, 33%, 92%, 1);
	filter: brightness(1);
}

.tab-container ul.menu>
li>
a:hover,
.tab-container ul.menu>
li.current_tab_item>

a {
	background: hsla(200, 33%, 92%, 1);
	filter: brightness(1.03);
}

/* 子ページ:tabchpt-container
-------------------------------------- */
/* (PC) */
@media print,
screen and (min-width: 768px) {
	.tabchpt-container {
		height: 0;
		visibility: hidden;
		opacity: 0;
		overflow: hidden;
	}

	.tabchpt-container.summon {
		height: auto;
		visibility: visible;
		opacity: 1;
	}
}
`);
document.getElementsByTagName('head')[0].appendChild(insertStyle);
})(); ///function invisibleTab:CSS();

(function () {
  //invisibleTab:JS
  let tabItems = Array.prototype.slice.call(document.querySelectorAll(".tab-item"));
  let tabChpts = Array.prototype.slice.call(document.querySelectorAll(".tabchpt-container"));
  let tabLinks = Array.prototype.slice.call(document.querySelectorAll(".tab-container .tab-link"));

  function tabClickEvent(tabLink) {
  tabLink.addEventListener('click', function (e) {
      var thsParent = this.parentNode;
      var tabChptId = this.getAttribute('href').substring(1); //'#' を取り除く
      var tabChpt = document.getElementById(tabChptId);
      var tabItem = thsParent;

      if (window.matchMedia('(min-width: 768px)').matches) {
        e.preventDefault();
      }
      var thsParent = this.parentNode;
      let hasCLASS = thsParent.classList.contains('current_tab_item');
      if (hasCLASS) {
        e.preventDefault();
      } else {
        //関連するタブコンテンツとタブアイテムを選択
        let targetTabChpt = document.querySelector(this.getAttribute('href'));
        let targetTabItem = this.parentNode;

        //GSAPのインスタンスを作成
        const timeline = gsap.timeline();
        timeline
          .to(targetTabChpt, {
            duration: 0.3,
            opacity: 0,
            onComplete: function () {
              tabChpts.forEach(function (tabChpt) {
                tabChpt.classList.remove('summon');
              });
              tabItems.forEach(function (tabItem) {
                tabItem.classList.remove('current_tab_item');
              });
            }
          })
          .add(() =& gt; {
          targetTabChpt.classList.add('summon');
          targetTabItem.classList.add('current_tab_item');
        })
      .to(targetTabChpt, {
        duration: 0.3,
        opacity: 1
      }, "<0.3"); //'<':前の要素から*秒後

    //タイムラインを再生
    timeline.play();
  }
});
} ///.Event('click')
tabLinks.forEach((link) =& gt; {
  tabClickEvent(link);
});
}) (); ///function invisibleTab:JS();

コードの概要

invisibleTab.jsは主に2つの部分から構成されます:

CSSの挿入: タブとタブコンテンツのスタイリングを定義します。
JavaScript機能: タブのクリックイベントを処理し、関連するタブコンテンツの表示と非表示を制御します。

1. CSSの挿入 (invisibleTab:CSS)

このセクションでは、新しいスタイルシートを動的にウェブページに追加します。スタイルシートはタブコンテナとタブアイテムのスタイリングを定義し、768px以上の画面幅で異なるスタイルを適用します。

コードの詳細:

.tab-container: タブコンテナの基本的なスタイリングを定義します。
@media print, screen and (min-width: 768px): 768px以上の画面幅で適用されるスタイルを定義します。主にフレックスボックスを使用してタブアイテムを行方向に配置します。
.tabchpt-container: タブコンテンツのスタイリングを定義します。PCビューでは、非アクティブなタブコンテンツは非表示になります。

2. JavaScript機能 (invisibleTab:JS)

このセクションでは、タブのクリックイベントを処理します。各タブリンクがクリックされると、関連するタブコンテンツが表示され、他のタブコンテンツが非表示になります。GSAPのタイムラインを使用して、タブコンテンツの表示と非表示のアニメーションを制御します。

コードの詳細:

tabClickEvent: タブリンクのクリックイベントを処理する関数です。クリックされたタブリンクの親要素がcurrent_tab_itemクラスを持っている場合(すなわち、現在アクティブなタブがクリックされた場合)、e.preventDefault();を呼び出してデフォルトの動作をキャンセルします。それ以外の場合、タブの切り替えとアニメーションが行われます。

まとめ

invisibleTab.jsは、PCとモバイルの両方で効果的なタブ切り替え機能を提供します。CSS部分はタブのスタイリングを管理し、JavaScript部分はタブの動的な動作を制御します。このコードは、ウェブページに整理されたタブ切り替え機能を迅速に追加するのに役立ちます。