10
社区成员




实现一个响应式的可切换选项卡,你可以使用如下的HTML、CSS和JavaScript代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Tabs</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="tabs">
<button class="tablink" onclick="openTab('tab1')">Tab 1</button>
<button class="tablink" onclick="openTab('tab2')">Tab 2</button>
<button class="tablink" onclick="openTab('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;
}
.tabs {
overflow: hidden;
background-color: #f1f1f1;
}
.tablink {
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: background-color 0.3s;
}
.tablink:hover {
background-color: #ddd;
}
.tabcontent {
display: none;
padding: 20px;
}
/* Responsive adjustments */
@media screen and (max-width: 600px) {
.tablink {
float: none;
width: 100%;
}
}
function openTab(tabName) {
// Hide all elements with class="tabcontent" by default
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Remove the class "active" from all elements with class="tablink"
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].classList.remove("active");
}
// Show the specific tab content
document.getElementById(tabName).style.display = "block";
// Add the class "active" to the button that opened the tab
event.currentTarget.classList.add("active");
}
// By default, open the first tab
document.getElementById("tab1").style.display = "block";
document.getElementsByClassName("tablink")[0].classList.add("active");
openTab
函数来显示对应的选项卡内容,并处理按钮的激活状态。