当前位置:首页 > JavaScript

js实现tab跳转

2026-02-02 17:08:13JavaScript

使用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();
});

注意事项

  1. 确保目标元素具有tabindex="0"(如自定义组件)
  2. 隐藏/禁用元素应排除在跳转队列外
  3. 对于单页应用,需要在动态内容加载后重新绑定事件
  4. 可结合CSS伪类:focus-visible优化视觉反馈
[tabindex]:focus-visible {
  outline: 2px solid #4285f4;
}

扩展方案

对于复杂场景可考虑使用第三方库如:

  • focus-trap-react(React专用)
  • a11y-dialog(模态框场景)
  • tabbable(获取可聚焦元素列表)

js实现tab跳转

标签: 跳转js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 //…

js实现轮播图

js实现轮播图

轮播图实现方法 基础HTML结构 <div class="slider"> <div class="slides"> <img src="image1.jpg…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现计算器

js实现计算器

实现基础计算器功能 使用JavaScript创建一个基础计算器需要处理数字输入、运算符逻辑和结果显示。以下是一个简单的实现示例: let currentInput = '0'; let previ…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Paren…

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval…