【问题标题】:Modal with tabindex="-1" gets focus on tab带有 tabindex="-1" 的模态将焦点放在选项卡上
【发布时间】:2013-10-04 13:56:30
【问题描述】:

我目前正在使用 Twitter Bootstrap,但在模态的 tabindex 中遇到了一个奇怪的问题:

我试图在模态框内的表单元素之间切换,但在最后一个按钮之后,焦点在返回关闭按钮之前消失了。我在控制台中添加了一行记录正在聚焦的元素,结果证明它是模态本身,即使它有tabindex="-1"。

我无法分享我的代码,但快速浏览一下 Bootstrap 文档告诉我,这也发生在他们的示例模式中。问题是可重现的:

  1. 访问http://getbootstrap.com/2.3.2/javascript.html#modals
  2. 打开演示模式(“启动演示模式”按钮)
  3. 选项卡浏览字段。在“保存更改”返回关闭按钮之前,您会失去焦点。

只要模态(或实际上带有tabindex="-1" 的任何元素)获得焦点,将其放入控制台将记录。

$('[tabindex="-1"]').focus(function(){
    console.log('Focus is on an element with negative tabindex')
});

(显然,当您单击模式时它也会记录它,但这超出了范围)。

为什么会这样?我怎样才能防止这种情况?这是浏览器错误、Twitter Bootstrap 的错误/功能,还是完全其他原因?

【问题讨论】:

    标签: jquery twitter-bootstrap tabindex


    【解决方案1】:

    有趣的发现。它似乎是引导程序引入的某种错误或行为;选项卡索引 -1 的行为非常奇怪。

    这里有一个使用 jQuery 的解决方法,它涉及在模式的第一个和最后一个可选项卡元素上设置 first 和 last id。

    $('#myModal').keydown(function(e){
      if($('#last').is(":focus") && (e.which || e.keyCode) == 9){
        e.preventDefault();
        $('#first').focus();
      }
    });
    

    例子

    http://www.bootply.com/96858

    【讨论】:

    • 太好了,谢谢。不得不使用解决方法与真正解决问题总是很遗憾,但这似乎像我想要的那样工作:)
    【解决方案2】:

    感谢特雷弗。这是我的最终代码:

    $('.modal').keydown(function(e){
            var $focusable = $(this).find("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])");
            if($focusable.last().is(":focus") && !e.shiftKey && e.key == "Tab"){
                    e.preventDefault();
                    $focusable.first().focus();
            }
            else
                if($focusable.first().is(":focus") && e.shiftKey  && e.key == "Tab"){
                e.preventDefault();
                $focusable.last().focus();
            }
    
        });
    

    【讨论】:

      【解决方案3】:

      实际上专注于你的主模态div,你可以通过下面的代码检查它

      #yourModalId:focus
      {
          background-color:yellow;
          border:1px solid red;
      }
      

      HTML 代码

       <div id="yourModalId" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 2011-06-21
        • 1970-01-01
        相关资源
        最近更新 更多