Menu
CoddyTech

选项卡

本课属于 Coddy HTML 学习旅程的“JavaScript 实战”单元。第 1 课,共 27 课。

选项卡可以让用户在不离开页面的情况下切换不同的内容。在单元 4 中,我们用 HTML 和 CSS 创建了选项卡。现在我们来使用 JavaScript。 

要点:

  1. 我们使用 display 属性(none / block)来隐藏和显示元素。
  2. 用户点击选项卡时,我们会调用函数并传入选项卡的 ID。
  1. 在函数内部,我们使用 querySelectorAll + forEach 来隐藏所有标签内容。
  2. 最后,我们显示与 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>
challenge icon

挑战

简单

我们已经编写好了让标签页正常工作的 JavaScript 函数。你的任务是: 

  1. 为每个标签页按钮添加 onclick 属性,点击标签页时显示对应的内容。
  2. 调用函数 openTab()。
  3. 传入标签页内容的 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>
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

JavaScript 实战中的所有课

自己练习: Web 在线编辑器