js实现tab跳转
使用JavaScript实现Tab跳转
通过监听键盘事件实现Tab键跳转功能,以下是两种常见实现方式:
方法一:基础事件监听
通过keydown事件监听Tab键(keyCode为9),阻止默认行为并手动聚焦下一个元素。
document.addEventListener('keydown', function(e) {
if (e.key === 'Tab') {
e.preventDefault();
const focusableElements = document.querySelectorAll('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])');
const currentIndex = Array.from(focusableElements).indexOf(document.activeElement);
const nextIndex = (currentIndex + 1) % focusableElements.length;
focusableElements[nextIndex].focus();
}
});
方法二:增强版循环跳转
添加Shift键判断实现反向跳转,并处理边界情况。
document.addEventListener('keydown', function(e) {
if (e.key !== 'Tab') return;
const focusable = Array.from(
document.querySelectorAll('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])')
).filter(el => !el.disabled && !el.hidden);
if (!focusable.length) return;
e.preventDefault();
const currentIndex = focusable.indexOf(document.activeElement);
let nextIndex = 0;
if (currentIndex >= 0) {
const direction = e.shiftKey ? -1 : 1;
nextIndex = (currentIndex + direction + focusable.length) % focusable.length;
}
focusable[nextIndex].focus();
});
注意事项
- 确保目标元素具有
tabindex="0"(如自定义组件) - 隐藏/禁用元素应排除在跳转队列外
- 对于单页应用,需要在动态内容加载后重新绑定事件
- 可结合CSS伪类
:focus-visible优化视觉反馈
[tabindex]:focus-visible {
outline: 2px solid #4285f4;
}
扩展方案
对于复杂场景可考虑使用第三方库如:
- focus-trap-react(React专用)
- a11y-dialog(模态框场景)
- tabbable(获取可聚焦元素列表)






