键盘导航是网站导航的一个重要功能,因为它可以改善用户体验。
KeyboardTrap是一个简单的Vue 3/2指令,可以在你的应用程序中实现键盘导航。这个指令最好的部分是它可以防止用户将焦点从容器或组件上移开,这被称为 "键盘陷阱"。
基本用法。
1.导入并注册该指令。
// Vue 3
import { createApp } from 'vue';
import { VueKeyboardTrapDirectivePlugin } from '@pdanpdan/vue-keyboard-trap';
import App from './App.vue';
const app = createApp(App);
app.use(VueKeyboardTrapDirectivePlugin, {
// options
});
app.mount('#app');
// Vue 2
import Vue from 'vue';
import { VueKeyboardTrapDirectivePlugin } from '@pdanpdan/vue-keyboard-trap';
import App from './App.vue';
Vue.use(VueKeyboardTrapDirectivePlugin, {
// options
});
new Vue({
el: '#app',
});
2.启用/禁用元素上的键盘导航。
<div v-kbd-trap="directiveEnabled">
...
</div>
3.可用的选项。
app.use(VueKeyboardTrapDirectivePlugin, {
// snake-case name of the directive (without `v-` prefix)
name: 'kbd-trap',
// CSS selector for focusable elements
focusableSelector: [
':focus',
'a[href]:not([tabindex^="-"])',
'area[href]:not([tabindex^="-"])',
'input:not([disabled]):not([tabindex^="-"])',
'select:not([disabled]):not([tabindex^="-"])',
'textarea:not([disabled]):not([tabindex^="-"])',
'button:not([disabled]):not([tabindex^="-"])',
'iframe:not([tabindex^="-"])',
'[tabindex]:not([tabindex^="-"])',
'[contenteditable]:not([tabindex^="-"]):not([contenteditable="false"])',
'[class*="focusable"]:not([disabled]):not([tabindex^="-"])',
].join(','),
// CSS selector for elements that should not respond to roving key navigation
rovingSkipSelector: [
'input:not([disabled]):not([type="button"]):not([type="checkbox"]):not([type="file"]):not([type="image"]):not([type="radio"]):not([type="reset"]):not([type="submit"])',
'select:not([disabled])',
'select:not([disabled]) *',
'textarea:not([disabled])',
'[contenteditable]:not([contenteditable="false"])',
'[contenteditable]:not([contenteditable="false"]) *',
].join(','),
// CSS selector that will be applied in .roving.grid mode to exclude elements - must be a series of :not() selectors
gridSkipSelector: [
':not([disabled])',
':not([tabindex^="-"])',
].join(''),
// CSS selector for the elements that should be autofocused
autofocusSelector: [
'[autofocus]:not([disabled]):not([autofocus="false"])',
'[data-autofocus]:not([disabled]):not([data-autofocus="false"])',
].join(','),
// tabIndex value to be used when trap element has a tabIndex of -1 and has no `tabindex` attribute
trapTabIndex: -9999,
});
预览。
更改日志。
v1.0.15 (09/30/2022)
- 修复:增加与Vue 2.7的兼容性
The postVue Directive for Keyboard Navigation - KeyboardTrapappeared first onVue Script.