10
社区成员




创建选项卡标题(或标签页)需要结合CSS和JavaScript来实现。以下是一个简单的示例,展示如何创建基本的选项卡标题功能。
<!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>
/* 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%;
}
}
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");
openTab
函数来显示对应的选项卡内容,并处理按钮的激活状态。