当前位置:首页 > JavaScript

js实现tab跳转

2026-04-07 10:49:56JavaScript

实现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.keyCodeevent.which作为备用方案。

document.addEventListener('keydown', function(event) {
    const key = event.key || event.keyCode;
    if (key === 'Tab' || key === 9) {
        event.preventDefault();
        // 跳转逻辑
    }
});

禁用特定元素的Tab跳转

通过设置tabindex="-1"或动态移除tabindex属性可以禁用某些元素的Tab跳转。

js实现tab跳转

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

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

相关文章

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const cha…

js实现继承

js实现继承

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

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

vue实现点击跳转

vue实现点击跳转

路由跳转(Vue Router) 在Vue项目中通过vue-router实现页面跳转是最常见的方式。确保已安装并配置路由: // 路由配置示例(router/index.js) import { c…

js实现吸色

js实现吸色

使用Canvas实现吸色功能 通过Canvas的getImageData方法获取像素颜色数据。创建一个Canvas元素,将目标图像绘制到Canvas上,通过鼠标事件获取坐标对应的颜色值。 c…

js实现滚动

js实现滚动

实现滚动效果的方法 在JavaScript中实现滚动效果可以通过多种方式完成,以下是一些常见的方法: 使用window.scrollTo() window.scrollTo()方法可以将页面滚动到指…