display: none切换时如何保持布局稳定
使用css类控制显隐是基础做法,但直接隐藏会导致高度塌陷。通过设置min-height或固定高度可以解决。

如何为选项卡添加键盘导航支持
除了鼠标点击,还需要处理键盘事件。通过监听keydown并判断ArrowLeft和ArrowRight来切换焦点。

基于当前选中状态的具体问题
当用户快速连续点击不同标签时,需要确保状态同步且无闪烁。
<meta charset="UTF-8"><title>Tab Component</title><style>
.tab-container {
width: 300px;
border: 1px solid #ccc;
font-family: sans-serif;
}
.tab-list {
display: flex;
list-style: none;
padding: 0;
margin: 0;
border-bottom: 1px solid #ccc;
}
.tab-item {
padding: 10px 20px;
cursor: pointer;
background: #f0f0f0;
border: 1px solid transparent;
border-bottom: none;
}
.tab-item.active {
background: #fff;
border-color: #ccc;
border-bottom: 1px solid #fff;
margin-bottom: -1px;
}
.tab-content {
padding: 20px;
min-height: 150px; /* 关键:防止内容高度变化导致跳动 */
border: 1px solid #ccc;
border-top: none;
}
.tab-pane {
display: none;
}
.tab-pane.active {
display: block;
}
</style><div class="tab-container">
<ul class="tab-list" role="tablist">
<li class="tab-item active" role="tab" aria-selected="true" tabindex="0" data-target="pane1">Tab 1</li>
<li class="tab-item" role="tab" aria-selected="false" tabindex="-1" data-target="pane2">Tab 2</li>
<li class="tab-item" role="tab" aria-selected="false" tabindex="-1" data-target="pane3">Tab 3</li>
</ul>
<div class="tab-content">
<div id="pane1" class="tab-pane active" role="tabpanel">Content 1</div>
<div id="pane2" class="tab-pane" role="tabpanel">Content 2</div>
<div id="pane3" class="tab-pane" role="tabpanel">Content 3</div>
</div>
</div>
<script>
const tabs = document.querySelectorAll('.tab-item');
const panes = document.querySelectorAll('.tab-pane');
function switchTab(selectedTab) {
// 移除所有激活状态
tabs.forEach(tab => {
tab.classList.remove('active');
tab.setAttribute('aria-selected', 'false');
tab.setAttribute('tabindex', '-1');
});
panes.forEach(pane => pane.classList.remove('active'));
// 激活选中的Tab
selectedTab.classList.add('active');
selectedTab.setAttribute('aria-selected', 'true');
selectedTab.setAttribute('tabindex', '0');
// 显示对应的面板
const targetId = selectedTab.getAttribute('data-target');
document.getElementById(targetId).classList.add('active');
}
// 绑定点击事件
tabs.forEach(tab => {
tab.addEventListener('click', () => switchTab(tab));
});
// 绑定键盘事件
document.querySelector('.tab-list').addEventListener('keydown', (e) => {
const currentTab = document.activeElement;
if (!currentTab.classList.contains('tab-item')) return;
let index = Array.from(tabs).indexOf(currentTab);
let nextIndex;
if (e.key === 'ArrowRight') {
nextIndex = (index + 1) % tabs.length;
} else if (e.key === 'ArrowLeft') {
nextIndex = (index - 1 + tabs.length) % tabs.length;
} else {
return;
}
e.preventDefault();
tabs[nextIndex].focus();
switchTab(tabs[nextIndex]);
});
</script>

前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











