我有一个切换导航菜单,结构如下:
<li>
<a href="mylink.page">
<span class="text">Link Text</span>
<span tabindex="0" class="button"></span>
</a>
<ul>... children ... </ul>
</li>
span.text 包含链接文本,而 span.button 是用户可以单击或按键输入以切换嵌套 ul 的元素。
在菜单中切换(测试可访问性)时,我的浏览器(在 Windows 上的 Chrome 和 Firefox 的最新公开版本中都试过)关注容器 a,然后关注 span.text,最后关注 span.button。这是我想要的行为,但不希望容器“a”受到关注 - 直接转到 span.text。
注意:当聚焦于容器 'a' 时,按下回车键不会激活链接,只有子级 span 在聚焦时激活链接(我已经阻止链接在 span.button 上按下 enter 时工作,所以切换工作在按键输入上)。
这种行为很好,本质上是我想要的(跨度是通过按键输入激活的链接)期望我想在使用 Tab 键时跳过容器“a”并直接转到子跨度。
tabindex="-1"对吗?没有。将 tabindex="-1"添加到容器“a”时,span.text 不再获得焦点并且事件链接消失。浏览器关注容器“a”,然后跳过 span.text 到 span.button。这很奇怪(至少对我而言)。在我看来,tabindex="-1"用于在使用 Tab 键时跳过元素。
关于如何在容器“a”和子 span 的组合上使用 tabindex 以实现我上面所说的任何想法(在菜单中切换仅点击 span.name [具有事件链接] 和 span.button)?甚至是 javascript/jquery 解决方案?
注意:让 tabindex="0"似乎是跳转到 span.button 的唯一方法。
编辑:稍作修改后,我将 tabindex="0"放在容器 'a' 上,它在 Chrome 中运行良好。 Firefox 仍然专注于容器“a”。
最佳答案
在 jQuery 中,尝试:
$('a:has(span[tabindex])').on('focus', function () {
$(this).find('span[tabindex]').focus();
}).on('keypress', 'span[tabindex]', function (e) {
if(e.which === 13) {
this.click(); //this not $(this), to call native click method
//or: $(this).parent()[0].click();
}
});
对于 1.7 以下的 jQuery,尝试:
$('a:has(span[tabindex])').bind('focus', function () {
$(this).find('span[tabindex]')[0].focus(); // call js focus(), not jq
}).delegate('span[tabindex]', 'keypress', function (e) {
if (e.which === 13) {
this.click(); //this not $(this), to call native click method
//or: $(this).parent()[0].click();
}
});
关于jquery - <a> 上带有子项的 HTML tabindex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27970202/