按键循环焦点功能是指通过键盘(通常是Tab键或方向键)在页面元素间循环导航的功能。在子导航中实现这一功能时,通常需要:
// 错误示例 - 事件未绑定到正确元素
$(document).keydown(function(e) {
// 这样会监听整个文档的按键,可能干扰其他功能
});
// 正确做法 - 只绑定到导航容器
$('.sub-nav-container').on('keydown', function(e) {
// 处理导航逻辑
});
// 需要阻止Tab键默认行为以实现自定义循环
$('.sub-nav-container').on('keydown', function(e) {
if (e.key === 'Tab') {
e.preventDefault();
// 自定义焦点逻辑
}
});
<!-- 错误的HTML结构 -->
<div class="nav-item" tabindex="0">Item 1</div>
<div class="nav-item" tabindex="2">Item 2</div>
<div class="nav-item" tabindex="1">Item 3</div>
<!-- 正确的HTML结构 -->
<div class="nav-item" tabindex="0">Item 1</div>
<div class="nav-item" tabindex="0">Item 2</div>
<div class="nav-item" tabindex="0">Item 3</div>
// 对于动态加载的子导航项,需要使用事件委托
$('.sub-nav-container').on('keydown', '.nav-item', function(e) {
// 处理逻辑
});
$(document).ready(function() {
const $navItems = $('.sub-nav-container .nav-item');
// 初始化第一个可聚焦元素
$navItems.first().attr('tabindex', '0');
$('.sub-nav-container').on('keydown', function(e) {
const $current = $(document.activeElement);
const currentIndex = $navItems.index($current);
// 处理左右方向键
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
e.preventDefault();
let nextIndex;
if (e.key === 'ArrowLeft') {
nextIndex = currentIndex > 0 ? currentIndex - 1 : $navItems.length - 1;
} else {
nextIndex = currentIndex < $navItems.length - 1 ? currentIndex + 1 : 0;
}
$navItems.eq(nextIndex).attr('tabindex', '0').focus();
$navItems.not($navItems.eq(nextIndex)).attr('tabindex', '-1');
}
// 处理Tab键循环
if (e.key === 'Tab') {
e.preventDefault();
let nextIndex;
if (e.shiftKey) { // Shift+Tab
nextIndex = currentIndex > 0 ? currentIndex - 1 : $navItems.length - 1;
} else { // Tab
nextIndex = currentIndex < $navItems.length - 1 ? currentIndex + 1 : 0;
}
$navItems.eq(nextIndex).attr('tabindex', '0').focus();
$navItems.not($navItems.eq(nextIndex)).attr('tabindex', '-1');
}
});
});
通过以上方法和代码示例,应该能够解决大多数子导航按键循环焦点功能的问题。如果仍有特定问题,可能需要针对具体实现进行更详细的调试。
没有搜到相关的文章