效果图
![效果图](https://img-blog.csdnimg.cn/4871cca475cf4faaa600e1e15a3ad3e1.jpeg#pic_center)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Tab 选项卡</title>
</head>
<body>
<main class="container">
<div class="tab-container">
<div class="tabs">
<div id="tab1" class="tab active">选项一</div>
<div id="tab2" class="tab">选项二</div>
<div id="tab3" class="tab">选项三</div>
</div>
<div class="tab-content">
<div data-tab="tab1" style="display: block">
<h2>选项 1 内容</h2>
</div>
<div data-tab="tab2" style="display: none">
<h2>选项 2 内容</h2>
</div>
<div data-tab="tab3" style="display: none">
<h2>选项 3 内容</h2>
</div>
</div>
</div>
</main>
<script src="index.js"></script>
</body>
</html>
css
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: Helvetica, "PingFang SC", "Microsoft Yahei", sans-serif;
}
body {
background: #f0f0f3;
color: #808b9f;
}
.container {
display: flex;
align-items: center;
justify-content: center;
width: 100vw;
height: 100vh;
min-width: 375px;
overflow: auto;
}
.tab-container {
padding: 24px;
width: 50%;
}
.tabs {
padding: 4px;
border-radius: 5px;
background: #f0f0f3;
box-shadow: -1px -1px 3px #ffffff, 1.5px 1.5px 3px rgba(174, 174, 192, 0.4);
display: flex;
}
.tab {
padding: 12px 36px;
cursor: pointer;
transition: 0.3s;
}
.tab.active {
border-radius: 5px;
background: #eeeeee;
box-shadow: inset -1px -1px 1px rgba(255, 255, 255, 0.7),
inset 1px 1px 2px rgba(174, 174, 192, 0.2);
color: #a7b4cc;
}
.tab-content {
margin-top: 36px;
padding: 36px;
border-radius: 16px;
background: #f0f0f3;
box-shadow: -10px -10px 30px #ffffff, 10px 10px 30px rgba(174, 174, 192, 0.4);
}
.tab-content > div {
animation: fadeIn 1.3s;
}
.tab-content h2 {
margin-bottom: 24px;
font-weight: 400;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@media (max-width: 838px) {
.tab-container {
width: 100%;
}
}
@media (min-width: 375px) and (max-width: 418px) {
.tab {
padding: 12px 24px;
}
}
js
const tabContainer = document.querySelector(".tabs");
const tabs = document.querySelectorAll(".tab");
const tabContents = document.querySelectorAll(".tab-content > *");
tabContainer.addEventListener("click", ({ target: currentTab }) => {
tabs.forEach((tab) => {
tab.classList.remove("active");
});
currentTab.classList.add("active");
changeTab(currentTab.id);
});
const changeTab = (tabId) => {
const newTab = document.querySelector(`div[data-tab=${tabId}]`);
tabContents.forEach((content) => {
content.style.display = "none";
});
newTab.style.display = "block";
};