Menu
Coddy logo textTech

タブ

CoddyのHTMLジャーニー「JavaScript in Action」セクションの一部 — レッスン 1/27。

タブを使用すると、ユーザーはページを離れることなく、異なるコンテンツを切り替えることができます。セクション4では、HTMLとCSSを使用してこれらを作成しました。今回はJavaScriptを使用します。 

重要なポイント:

  1. 要素を非表示にしたり表示したりするために、displayプロパティ (none / block) を使用します。
  2. ユーザーがタブをクリックしたときに、関数を呼び出し、タブのIDを渡します。
  1. 関数内では、<strong>querySelectorAll</strong> + <strong>forEach</strong>を使用して、すべてのタブコンテンツを非表示にします。
  2. 最後に、IDが一致するものを表示します
<div class="tabs">
  <button class="tab" onclick="openTab('services')">サービス</button>
  <button class="tab" onclick="openTab('contact')">お問い合わせ</button>
</div>

<div id="services" class="tab-content">当社のサービスはこちらに記載されています。</div>
<div id="contact" class="tab-content" style="display:none;">contact@example.com までお問い合わせください。</div>

<script>
  function openTab(tabId) {
    // すべてのタブコンテンツを非表示にする
    document.querySelectorAll('.tab-content').forEach(el => el.style.display = 'none');
    // 選択されたタブを表示する
    document.getElementById(tabId).style.display = 'block';
  }
</script>
challenge icon

チャレンジ

簡単

タブを機能させるためのJavaScript関数はすでに作成されています。あなたのタスクは以下の通りです: 

  1. 各タブボタンに onclick 属性を追加し、タブをクリックしたときに正しいコンテンツが表示されるようにします。
  2. 関数 openTab() を呼び出します。
  3. タブコンテンツのid(homeabout、または contact)を渡します。

自分で試してみよう

<!DOCTYPE html>
<html>
<head>
  <title>Simple Tabs Example</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="tabs">
    <!-- Each button calls the function and passes the tab's ID -->
    <button class="tab" >Home</button>
    <button class="tab" >About</button>
    <button class="tab" >Contact</button>
  </div>

  <!-- By default, only "Home" is visible -->
  <div id="home" class="tab-content">Welcome to the homepage!</div>
  <div id="about" class="tab-content" style="display:none;">Learn more about us here.</div>
  <div id="contact" class="tab-content" style="display:none;">Get in touch with us.</div>

  <script src="script.js"></script>
</body>
</html>
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

JavaScript in Actionのすべてのレッスン