js实现tab键的效果
使用JavaScript实现Tab键效果
实现Tab键效果通常用于在表单或自定义组件中切换焦点。以下是几种常见方法:
监听keydown事件
通过监听元素的keydown事件,检测Tab键(keyCode 9)并手动控制焦点切换:
document.addEventListener('keydown', function(event) {
if (event.key === 'Tab') {
event.preventDefault();
const focusableElements = document.querySelectorAll('input, button, select, textarea, [href], [tabindex]:not([tabindex="-1"])');
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
if (event.shiftKey && document.activeElement === firstElement) {
lastElement.focus();
} else if (!event.shiftKey && document.activeElement === lastElement) {
firstElement.focus();
}
}
});
使用tabindex属性
为元素设置tabindex属性控制Tab顺序:
<div tabindex="0">可聚焦元素1</div>
<div tabindex="1">可聚焦元素2</div>
const elements = document.querySelectorAll('[tabindex]');
elements.forEach(el => {
el.addEventListener('keydown', (e) => {
if (e.key === 'Tab') {
// 自定义处理逻辑
}
});
});
自定义Tab组件
创建可Tab切换的UI组件:
class TabComponent {
constructor(container) {
this.tabs = Array.from(container.querySelectorAll('.tab'));
this.panels = Array.from(container.querySelectorAll('.panel'));
this.init();
}
init() {
this.tabs.forEach(tab => {
tab.addEventListener('keydown', e => {
if (e.key === 'Tab') {
this.switchTab(tab);
}
});
});
}
switchTab(selectedTab) {
// 切换逻辑
}
}
无障碍实现
确保Tab导航符合无障碍标准:

function handleTabNavigation() {
const focusable = Array.from(document.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
)).filter(el => !el.disabled && !el.hidden);
document.addEventListener('keydown', e => {
if (e.key !== 'Tab') return;
const currentIndex = focusable.indexOf(document.activeElement);
if (currentIndex === -1) return;
const nextIndex = e.shiftKey ?
(currentIndex - 1 + focusable.length) % focusable.length :
(currentIndex + 1) % focusable.length;
focusable[nextIndex].focus();
e.preventDefault();
});
}
这些方法可以根据具体需求进行调整,实现不同的Tab键导航效果。






