@neosjs/focus-trap
焦点圈定组件(无渲染组件)。将 Tab 焦点限制在指定容器内循环,防止用户通过键盘把焦点移出弹层,常用于 Dialog、Modal 等可访问性场景。
安装
sh
pnpm add @neosjs/focus-trapsh
npm i @neosjs/focus-trapsh
yarn add @neosjs/focus-trap快速上手
组件不渲染任何 DOM,通过默认插槽接收容器元素;trapped 为 true 时开始圈定焦点,为 false 时释放并把焦点还原到圈定前的元素。
vue
<script setup lang="ts">
import { NeosFocusTrap } from '@neosjs/focus-trap'
import { ref } from 'vue'
const trapped = ref(false)
</script>
<template>
<button @click="trapped = true">
打开并圈定焦点
</button>
<NeosFocusTrap :trapped="trapped" loop @release-requested="trapped = false">
<div tabindex="-1">
<button>按钮 1</button>
<button>按钮 2</button>
<button>按钮 3</button>
</div>
</NeosFocusTrap>
</template>工作机制
- 圈定期间,Tab / Shift+Tab 只会在容器内的可聚焦元素之间移动;
loop开启后在首尾元素之间循环。 - 按下 ESC 会触发
releaseRequested事件,由外部决定是否将trapped置为false。 - 释放时会自动把焦点还原到圈定前的元素。
- 默认插槽为作用域插槽,提供
handle-keydown,可绑定到容器上处理键盘事件。
Props
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| loop | boolean | false | 焦点是否在容器首尾循环 |
| trapped | boolean | false | 是否圈定焦点 |
| focus-trap-el | HTMLElement | — | 直接指定圈定的容器元素(不通过插槽时使用) |
| focus-start-el | 'container' | 'first' | HTMLElement | 'first' | 圈定时初始聚焦的目标 |
Emits
| 事件名 | 参数 | 说明 |
|---|---|---|
| focus-after-trapped | (event: Event) | 焦点圈定完成后触发 |
| focus-after-released | (event: CustomEvent) | 焦点释放后触发 |
| focusin | (event: FocusEvent) | 容器内获得焦点时触发 |
| focusout | (event: FocusEvent) | 未圈定状态下,焦点移出容器时触发 |
| focusout-prevented | (event: CustomEvent) | 焦点即将移出容器被拦截时触发,可通过 event.detail.focusReason 判断原因 |
| release-requested | (event: KeyboardEvent) | 圈定期间按下 ESC 请求释放时触发 |
Slots
| 插槽名 | 参数 | 说明 |
|---|---|---|
| default | handle-keydown: (e: KeyboardEvent) => void | 圈定的容器元素,作用域参数为键盘事件处理函数 |