编写HTML/CSS/JS选项卡导航系统的最佳方法(无图像)
基于HTML标签的选项卡导航系统示例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>选项卡导航系统示例</title>
<style>
.tab-container {
display: flex;
justify-content: space-around;
}
.tab {
cursor: pointer;
padding: 10px;
}
.tab-content {
display: none;
padding: 20px;
}
.tab-content.active {
display: block;
}
</style>
</head>
<body>
<div class="tab-container">
<div class="tab active" onclick="showTab('tab-1')">选项卡1</div>
<div class="tab" onclick="showTab('tab-2')">选项卡2</div>
<div class="tab" onclick="showTab('tab-3')">选项卡3</div>
</div>
<div id="tab-1" class="tab-content active">
<h2>选项卡1内容</h2>
<p>这是选项卡1的内容。</p>
</div>
<div id="tab-2" class="tab-content">
<h2>选项卡2内容</h2>
<p>这是选项卡2的内容。</p>
</div>
<div id="tab-3" class="tab-content">
<h2>选项卡3内容</h2>
<p>这是选项卡3的内容。</p>
</div>
<script>
function showTab(tabId) {
var tabs = document.getElementsByClassName('tab');
for (var i = 0; i< tabs.length; i++) {
var tab = tabs[i];
var tabContent = document.getElementById(tab.innerHTML);
if (tab.innerHTML === tabId) {
tab.classList.add('active');
tabContent.classList.add('active');
} else {
tab.classList.remove('active');
tabContent.classList.remove('active');
}
}
}
</script>
</body>
</html>
基于JavaScript的选项卡导航系统示例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>选项卡导航系统示例</title>
<style>
.tab-container {
display: flex;
justify-content: space-around;
}
.tab {
cursor: pointer;
padding: 10px;
}
.tab-content {
display: none;
padding: 20px;
}
.tab-content.active {
display: block;
}
</style>
</head>
<body>
<div class="tab-container">
<div class="tab active" data-tab="tab-1">选项卡1</div>
<div class="tab" data-tab="tab-2">选项卡2</div>
<div class="tab" data-tab="tab-3">选项卡3</div>
</div>
<div id="tab-1" class="tab-content active">
<h2>选项卡1内容</h2>
<p>这是选项卡1的内容。</p>
</div>
<div id="tab-2" class="tab-content">
<h2>选项卡2内容</h2>
<p>这是选项卡2的内容。</p>
</div>
<div id="tab-3" class="tab-content">
<h2>选项卡3内容</h2>
<p>这是选项卡3的内容。</p>
</div>
<script>
var tabs = document.getElementsByClassName('tab');
for (var i = 0; i< tabs.length; i++) {
var tab = tabs[i];
tab.addEventListener('click', function() {
var tabId = this.getAttribute('data-tab');
var tabContents = document.getElementsByClassName('tab-content');
for (var j = 0; j < tabContents.length; j++) {
var tabContent = tabContents[j];
if (tabContent.id === tabId) {
tabContent.classList.add('active');
} else {
tabContent.classList.remove('active');
}
}
var tab = document.querySelector('.tab[data-tab="' + tabId + '"]');
tab.classList.add('active');
});
}
</script>
</body>
</html>
领取专属 10元无门槛券
手把手带您无忧上云