以下是一个使用纯CSS和JavaScript编写的简单Tab标签页示例,包括基本的样式和功能。
### HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Tabs</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="tabs">
<button class="tab-link" onclick="openTab(event, 'Tab1')">Tab 1</button>
<button class="tab-link" onclick="openTab(event, 'Tab2')">Tab 2</button>
<button class="tab-link" onclick="openTab(event, 'Tab3')">Tab 3</button>
<div id="Tab1" class="tab-content">
<h3>Tab 1 Content</h3>
<p>This is the content of Tab 1.</p>
</div>
<div id="Tab2" class="tab-content">
<h3>Tab 2 Content</h3>
<p>This is the content of Tab 2.</p>
</div>
<div id="Tab3" class="tab-content">
<h3>Tab 3 Content</h3>
<p>This is the content of Tab 3.</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
### CSS (style.css)
.tabs {
display: flex;
flex-direction: column;
}
.tab-link {
background-color: #f1f1f1;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
.tab-link:hover {
background-color: #ddd;
}
.tab-content {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
.tab-content.active {
display: block;
}
### JavaScript (script.js)
function openTab(evt, tabName) {
// 获取所有元素中有 tab-content 类的元素,并隐藏它们
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tab-content");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// 获取所有元素中有 tab-link 类的元素,并移除 "active" 类
tablinks = document.getElementsByClassName("tab-link");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// 显示当前标签页的内容
document.getElementById(tabName).style.display = "block";
// 添加 "active" 类到当前点击的标签上
evt.currentTarget.className += " active";
}
在这个示例中,我们创建了一个带有三个标签的Tab页。每个标签都有一个点击事件处理器,用于显示对应的内容并激活当前标签。CSS负责基本的样式,JavaScript则处理标签的显示逻辑。