タブ
CoddyのHTMLジャーニー「JavaScriptの実践」セクションの一部。レッスン 1/27。
タブを使うと、ページを離れずに異なるコンテンツを切り替えられます。HTMLとCSSだけでも作成できますが、ここではJavaScriptを使います。
重要なポイント:
- displayプロパティ(
none/block)を使って、要素を非表示にしたり表示したりします。 - ユーザーがタブをクリックしたとき、関数を呼び出し
- 関数内では、すべてのタブのコンテンツを非表示にするために、
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プレイグラウンド