如何使用 CSS 和 JavaScript 创建选项卡标题

2401_83810323 2024-07-04 09:52:57

创建选项卡标题(或标签页)需要结合CSS和JavaScript来实现。以下是一个简单的示例,展示如何创建基本的选项卡标题功能。

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tab Titles Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>

<div class="tab">
  <button class="tablinks" onclick="openTab(event, 'tab1')">Tab 1</button>
  <button class="tablinks" onclick="openTab(event, 'tab2')">Tab 2</button>
  <button class="tablinks" onclick="openTab(event, 'tab3')">Tab 3</button>
</div>

<div id="tab1" class="tabcontent">
  <h3>Tab 1 Content</h3>
  <p>This is the content of tab 1.</p>
</div>

<div id="tab2" class="tabcontent">
  <h3>Tab 2 Content</h3>
  <p>This is the content of tab 2.</p>
</div>

<div id="tab3" class="tabcontent">
  <h3>Tab 3 Content</h3>
  <p>This is the content of tab 3.</p>
</div>

<script src="script.js"></script>
</body>
</html>

 

CSS (styles.css)

/* Basic reset and styling */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

.tab {
  overflow: hidden;
  background-color: #f1f1f1;
}

.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 10px 20px;
  transition: background-color 0.3s;
}

.tab button:hover {
  background-color: #ddd;
}

.tab button.active {
  background-color: #ccc;
}

.tabcontent {
  display: none;
  padding: 20px;
}

/* Responsive adjustments */
@media screen and (max-width: 600px) {
  .tab button {
    width: 100%;
  }
}

 

JavaScript (script.js)

function openTab(evt, tabName) {
  var i, tabcontent, tablinks;

  // 获取所有选项卡内容并隐藏它们
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }

  // 获取所有选项卡按钮并移除激活状态
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].classList.remove("active");
  }

  // 显示特定选项卡内容并激活选项卡按钮
  document.getElementById(tabName).style.display = "block";
  evt.currentTarget.classList.add("active");
}

// 默认打开第一个选项卡
document.getElementById("tab1").style.display = "block";
document.getElementsByClassName("tablinks")[0].classList.add("active");

 

解释

  • HTML部分包含了选项卡按钮和各个选项卡的内容。
  • CSS部分定义了选项卡按钮和内容的基本样式,包括激活状态的样式变化。
  • JavaScript部分实现了选项卡切换功能。通过点击按钮触发openTab函数来显示对应的选项卡内容,并处理按钮的激活状态。
...全文
162 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

10

社区成员

发帖
与我相关
我的任务
社区描述
一个讨论休闲、娱乐和工作生活平衡的在线社区。
前端软件工程 个人社区
社区管理员
  • 2401_83810323
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧