h5实现选项卡
使用HTML5和CSS实现选项卡
HTML5结合CSS可以轻松实现选项卡效果,无需JavaScript也能完成基本功能。以下是纯HTML+CSS的实现方法:
<div class="tab-container">
<input type="radio" name="tabs" id="tab1" checked>
<label for="tab1">选项卡1</label>
<div class="tab-content">内容1</div>
<input type="radio" name="tabs" id="tab2">
<label for="tab2">选项卡2</label>
<div class="tab-content">内容2</div>
<input type="radio" name="tabs" id="tab3">
<label for="tab3">选项卡3</label>
<div class="tab-content">内容3</div>
</div>
.tab-container {
display: flex;
flex-direction: column;
}
.tab-container input[type="radio"] {
display: none;
}
.tab-container label {
padding: 10px 20px;
background: #eee;
cursor: pointer;
order: 1;
}
.tab-content {
display: none;
padding: 20px;
order: 2;
}
.tab-container input[type="radio"]:checked + label {
background: #ddd;
}
.tab-container input[type="radio"]:checked + label + .tab-content {
display: block;
}
使用JavaScript增强交互
如果需要更灵活的交互效果,可以结合JavaScript实现:
<div class="tab-container">
<div class="tab-headers">
<button class="tab-header active" data-tab="tab1">选项卡1</button>
<button class="tab-header" data-tab="tab2">选项卡2</button>
<button class="tab-header" data-tab="tab3">选项卡3</button>
</div>
<div class="tab-content active" id="tab1">内容1</div>
<div class="tab-content" id="tab2">内容2</div>
<div class="tab-content" id="tab3">内容3</div>
</div>
.tab-headers {
display: flex;
border-bottom: 1px solid #ddd;
}
.tab-header {
padding: 10px 20px;
background: none;
border: none;
cursor: pointer;
}
.tab-header.active {
border-bottom: 2px solid blue;
}
.tab-content {
display: none;
padding: 20px;
}
.tab-content.active {
display: block;
}
document.querySelectorAll('.tab-header').forEach(header => {
header.addEventListener('click', () => {
// 移除所有active类
document.querySelectorAll('.tab-header, .tab-content').forEach(el => {
el.classList.remove('active');
});
// 添加active类到当前选项卡
header.classList.add('active');
const tabId = header.getAttribute('data-tab');
document.getElementById(tabId).classList.add('active');
});
});
响应式选项卡设计
针对移动设备优化的响应式选项卡:
@media (max-width: 768px) {
.tab-headers {
flex-direction: column;
}
.tab-header {
text-align: left;
border-bottom: 1px solid #eee;
}
.tab-header.active {
border-bottom: 2px solid blue;
border-left: none;
}
}
动画效果增强
为选项卡切换添加平滑过渡效果:
.tab-content {
opacity: 0;
height: 0;
overflow: hidden;
transition: opacity 0.3s ease, height 0.3s ease;
}
.tab-content.active {
opacity: 1;
height: auto;
}



