以下是实现Tab菜单切换内容的原生JavaScript和jQuery版本的代码示例:
原生JavaScript版本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tab Menu in JavaScript</title>
<style>
.tab-content { display: none; }
.tab-content.active { display: block; }
</style>
</head>
<body>
<div class="tabs">
<button class="tab" onclick="openTab(event, 'tab1')">Tab 1</button>
<button class="tab" onclick="openTab(event, 'tab2')">Tab 2</button>
<button class="tab" onclick="openTab(event, 'tab3')">Tab 3</button>
</div>
<div id="tab1" class="tab-content active">
<h3>Tab 1</h3>
<p>This is tab 1 content.</p>
</div>
<div id="tab2" class="tab-content">
<h3>Tab 2</h3>
<p>This is tab 2 content.</p>
</div>
<div id="tab3" class="tab-content">
<h3>Tab 3</h3>
<p>This is tab 3 content.</p>
</div>
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tab-content");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].className = tabcontent[i].className.replace("active", "");
}
tablinks = document.getElementsByClassName("tab");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace("active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
</body>
</html>
jQuery版本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tab Menu in jQuery</title>
<style>
.tab-content { display: none; }
.tab-content.active { display: block; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="tabs">
<button class="tab" data-tab="tab1">Tab 1</button>
<button class="tab" data-tab="tab2">Tab 2</button>
<button class="tab" data-tab="tab3">Tab 3</button>
</div>
<div id="tab1" class="tab-content active">
<h3>Tab 1</h3>
<p>This is tab 1 content.</p>
</div>
<div id="tab2" class="tab-content">
<h3>Tab 2</h3>
<p>This is tab 2 content.</p>
</