js实现tab跳转
实现Tab跳转的基本思路
使用JavaScript监听键盘事件,当按下Tab键时,将焦点切换到下一个可聚焦元素。常见的可聚焦元素包括<input>、<select>、<textarea>和带有tabindex属性的元素。
document.addEventListener('keydown', function(event) {
if (event.key === 'Tab') {
event.preventDefault();
const focusableElements = document.querySelectorAll('input, select, textarea, button, [tabindex]:not([tabindex="-1"])');
const currentElement = document.activeElement;
let currentIndex = Array.from(focusableElements).indexOf(currentElement);
if (currentIndex === -1) {
focusableElements[0].focus();
} else {
const nextIndex = (currentIndex + 1) % focusableElements.length;
focusableElements[nextIndex].focus();
}
}
});
自定义Tab顺序
通过tabindex属性可以自定义元素的Tab顺序。tabindex="0"表示元素可聚焦且按自然顺序排列,tabindex="-1"表示元素不可通过Tab键聚焦。
<input type="text" tabindex="1">
<button tabindex="3">Button</button>
<select tabindex="2">
<option>Option 1</option>
</select>
处理动态内容
对于动态添加的元素,需要重新获取可聚焦元素列表。可以使用MutationObserver监听DOM变化。
const observer = new MutationObserver(function() {
focusableElements = document.querySelectorAll('input, select, textarea, button, [tabindex]:not([tabindex="-1"])');
});
observer.observe(document.body, { childList: true, subtree: true });
循环跳转
默认情况下,Tab键会在页面末尾停止。通过以下代码可以实现循环跳转:
const focusableElements = document.querySelectorAll('input, select, textarea, button, [tabindex]:not([tabindex="-1"])');
focusableElements[0].focus();
document.addEventListener('keydown', function(event) {
if (event.key === 'Tab') {
event.preventDefault();
const currentElement = document.activeElement;
let currentIndex = Array.from(focusableElements).indexOf(currentElement);
const nextIndex = (currentIndex + 1) % focusableElements.length;
focusableElements[nextIndex].focus();
}
});
反向Tab跳转(Shift+Tab)
通过检查event.shiftKey可以实现反向跳转。
document.addEventListener('keydown', function(event) {
if (event.key === 'Tab') {
event.preventDefault();
const focusableElements = document.querySelectorAll('input, select, textarea, button, [tabindex]:not([tabindex="-1"])');
const currentElement = document.activeElement;
let currentIndex = Array.from(focusableElements).indexOf(currentElement);
if (event.shiftKey) {
const prevIndex = (currentIndex - 1 + focusableElements.length) % focusableElements.length;
focusableElements[prevIndex].focus();
} else {
const nextIndex = (currentIndex + 1) % focusableElements.length;
focusableElements[nextIndex].focus();
}
}
});
兼容性处理
确保代码在旧版浏览器中正常工作,可以使用event.keyCode或event.which作为备用方案。
document.addEventListener('keydown', function(event) {
const key = event.key || event.keyCode;
if (key === 'Tab' || key === 9) {
event.preventDefault();
// 跳转逻辑
}
});
禁用特定元素的Tab跳转
通过设置tabindex="-1"或动态移除tabindex属性可以禁用某些元素的Tab跳转。

document.getElementById('no-tab').setAttribute('tabindex', '-1');






