CSS Tab 是一种使用 CSS 技术实现的页面布局方式,主要用于创建标签页(Tab)界面。通过 CSS 和 HTML 的结合,可以实现点击不同标签页切换显示不同内容的效果。
以下是一个简单的纯 CSS 实现的标签页示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Tab</title>
<style>
.tab {
display: flex;
}
.tab button {
background-color: #f1f1f1;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
}
.tab button:hover {
background-color: #ddd;
}
.tab button.active {
background-color: #ccc;
}
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
.tabcontent.active {
display: block;
}
</style>
</head>
<body>
<div class="tab">
<button class="tablinks active" 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 active">
<h3>Tab 1 Content</h3>
<p>This is the content for Tab 1.</p>
</div>
<div id="Tab2" class="tabcontent">
<h3>Tab 2 Content</h3>
<p>This is the content for Tab 2.</p>
</div>
<div id="Tab3" class="tabcontent">
<h3>Tab 3 Content</h3>
<p>This is the content for Tab 3.</p>
</div>
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].classList.remove("active");
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].classList.remove("active");
}
document.getElementById(tabName).classList.add("active");
evt.currentTarget.classList.add("active");
}
</script>
</body>
</html>
openTab
正确绑定到按钮的点击事件。active
类的添加和移除。id
,并与 JavaScript 函数中的 tabName
参数匹配。display
属性的设置。通过以上示例代码和解决方法,你应该能够实现一个基本的 CSS Tab 功能,并解决常见的切换和显示问题。
领取专属 10元无门槛券
手把手带您无忧上云