带有tabindex =“-1"的模态.专注于标签 [英] Modal with tabindex="-1" gets focus on tab
问题描述
此刻我正在使用Twitter Bootstrap,在模式的tabindex中遇到一个奇怪的问题:
I'm working with Twitter Bootstrap at the moment, and I'm encountering a strange problem in the tabindex of a modal:
我正在尝试在模式内的表单元素之间进行切换,但是在最后一个按钮之后,焦点消失了,然后才返回到关闭按钮.我在控制台中添加了一行,用于记录正在聚焦的元素,即使它具有tabindex="-1"
,它还是模态本身.
I'm trying to tab through the form elements inside the modal, but after the last button the focus disappeared before coming back to the close button. I added a line in console that logs which element is being focused, and it turned out to be the modal itself, even though it has tabindex="-1"
.
我无法共享我的代码,但是快速浏览Bootstrap文档告诉我,它们也出现在示例模式中.问题是可重现的:
I'm unable to share my code, but a quick look at the Bootstrap docs told me that it also happens in their example modal. The problem is reproducable:
- 访问 http://getbootstrap.com/2.3.2/javascript.html#modals
- 打开演示模式(启动演示模式"按钮)
- 在字段中选择标签.在保存更改"之后,您将失去焦点,然后又回到关闭按钮.
每当模式(或实际上任何带有tabindex="-1"
的元素)获得焦点时,将其记录在控制台中都会记录日志.
Putting this in console will log whenever the modal (or in fact any element with tabindex="-1"
) gains focus.
$('[tabindex="-1"]').focus(function(){
console.log('Focus is on an element with negative tabindex')
});
(显然,当您单击模式时,它也会记录下来,但这不在范围内.)
(It also logs it when you click on the modal obviously, but that's out of scope).
为什么会这样?我该如何预防呢?这是浏览器错误,还是Twitter Bootstrap的错误/功能,还是其他所有功能?
Why does this happen? How can I prevent this? Is this a browser bug, a bug/feature of Twitter Bootstrap, or something else entirely?
推荐答案
有趣的发现.这似乎是引导程序引入的某种错误或行为.标签索引-1的行为很奇怪.
Interesting find. It appears to be some sort of bug or behavior introduced by bootstrap; Very odd behavior for tab index -1.
这是使用jQuery的一种解决方法,其中涉及在模式的第一个和最后一个可选项卡的元素上设置first
和last
id.
Here is one work around using jQuery, which involves setting a first
and last
id on the first and last tab-able elements on the modal.
$('#myModal').keydown(function(e){
if($('#last').is(":focus") && (e.which || e.keyCode) == 9){
e.preventDefault();
$('#first').focus();
}
});
示例
这篇关于带有tabindex =“-1"的模态.专注于标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!