TAB选项卡最简单的html+js切换按钮切换对应div实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tab Example</title>
<style>
/* Style for the tabs */
.nav {
list-style: none;
padding: 0;
margin: 0;
display: flex;
}
.nav li {
padding: 10px 20px;
cursor: pointer;
background: #f1f1f1;
border: 1px solid #ccc;
margin-right: 5px;
}
.nav li.active {
background: #ddd;
border-bottom: 1px solid #ddd;
}
/* Style for tab content */
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
</style>
</head>
<body>
<ul class="nav">
<li id="tab1-btn" data-tab="tab1" class="active">Tab 1</li>
<li id="tab2-btn" data-tab="tab2">Tab 2</li>
<li id="tab3-btn" data-tab="tab3">Tab 3</li>
</ul>
<div id="tab1" class="tab-content active">
<h2>Content for Tab 1</h2>
<p>This is the content for the first tab.</p>
</div>
<div id="tab2" class="tab-content">
<h2>Content for Tab 2</h2>
<p>This is the content for the second tab.</p>
</div>
<div id="tab3" class="tab-content">
<h2>Content for Tab 3</h2>
<p>This is the content for the third tab.</p>
</div>
<script>
// JavaScript to handle tab switching
document.addEventListener('DOMContentLoaded', () => {
const tab1Btn = document.getElementById('tab1-btn');
const tab2Btn = document.getElementById('tab2-btn');
const tab3Btn = document.getElementById('tab3-btn');
const tab1Content = document.getElementById('tab1');
const tab2Content = document.getElementById('tab2');
const tab3Content = document.getElementById('tab3');
function handleTabClick(clickedBtn, contentToShow) {
const buttons = [tab1Btn, tab2Btn, tab3Btn];
const contents = [tab1Content, tab2Content, tab3Content];
// Remove active class from all tabs and contents
buttons.forEach(btn => btn.classList.remove('active'));
contents.forEach(content => content.classList.remove('active'));
// Add active class to the clicked tab and corresponding content
clickedBtn.classList.add('active');
contentToShow.classList.add('active');
}
tab1Btn.addEventListener('click', () => handleTabClick(tab1Btn, tab1Content));
tab2Btn.addEventListener('click', () => handleTabClick(tab2Btn, tab2Content));
tab3Btn.addEventListener('click', () => handleTabClick(tab3Btn, tab3Content));
});
</script>
</body>
</html>
This approach uses IDs to identify elements directly, which should make your element selection more reliable.