タブ
CoddyのHTMLジャーニー「JavaScriptの実践」セクションの一部。レッスン 1/27。
タブを使うと、ユーザーはページを離れずに異なるコンテンツを切り替えられます。セクション4では、HTMLとCSSを使ってタブを作りました。今回はJavaScriptを使います。
要点:
- displayプロパティ(
none/block)を使って、要素を非表示にしたり表示したりします。 - ユーザーがタブをクリックしたときに、関数を呼び出し、そのタブのIDを渡します。
- 関数内では、
querySelectorAll+forEachを使って、すべてのタブのコンテンツを非表示にします。 - 最後に、IDと一致するものを表示します。
<div class="tabs">
<button class="tab" onclick="openTab('services')">Services</button>
<button class="tab" onclick="openTab('contact')">Contact</button>
</div>
<div id="services" class="tab-content">Our services are listed here.</div>
<div id="contact" class="tab-content" style="display:none;">Contact us at contact@example.com.</div>
<script>
function openTab(tabId) {
// Hide all tab contents
document.querySelectorAll('.tab-content').forEach(el => el.style.display = 'none');
// Show the selected tab
document.getElementById(tabId).style.display = 'block';
}
</script>チャレンジ
簡単タブを動作させるJavaScript関数はすでに作成されています。あなたのタスク:
- 各タブボタンに
onclick属性を追加し、タブをクリックすると正しいコンテンツが表示されるようにする - 関数
openTab()を呼び出す。 - タブコンテンツのid(
home、about、またはcontact)を渡す。
自分で試してみよう
<!DOCTYPE html>
<html>
<head>
<title>Simple Tabs Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="tabs">
<!-- 各ボタンは関数を呼び出し、タブのIDを渡します -->
<button class="tab" >Home</button>
<button class="tab" >About</button>
<button class="tab" >Contact</button>
</div>
<!-- デフォルトでは、"Home" のみが表示されます -->
<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>このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
JavaScriptの実践のすべてのレッスン
自分で練習してみよう: Webプレイグラウンド