如何在Bootstrap模态框关闭后防止焦点集中在切换按钮上?

8
我有一个按钮可以切换 Bootstrap 模态框。按钮本身被包裹在一个 div 中,因此当鼠标悬停时会显示工具提示。
当我关闭模态框时,按钮会被聚焦,并且工具提示会在未悬停该元素的情况下显示出来。
<span data-toggle="tooltip" data-placement="top" data-title="Tooltip">
    <button  data-toggle="modal" data-target="#modal">Toggle</button>
</span>

 <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-hidden="true">
     <div class="modal-dialog">
         <div class="modal-content">
             <div class="modal-header">
                 <button type="button" class="close" data-dismiss="modal">&times;</button>
             </div>
             
             <div class="modal-body">
                 <p>lorem ispum dolor sit amet</p>
             </div>
             
             
             <div class="modal-footer">
                 <button type="button" class="btn btn-primary">Submit</button>
                 <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
             </div>
         </div>
     </div>
</div>

请看这里发生了什么:http://jsfiddle.net/6t3kxhLb/

目前我能想到的唯一解决方法是在hidden.bs.modal事件触发时模糊按钮。但是我对结果并不满意。

这是我的解决方法:

$('#modal').on('hidden.bs.modal', function(event){
    setTimeout(function(){
      $('[data-toggle="modal"]').blur();
    });
 });

你们知道如何避免模态窗口关闭时焦点在切换按钮上吗?

2
请注意,模态框之所以进行此聚焦是为了良好的可访问性。否则,用户在模态框关闭后会失去页面的哪一部分,这会让人感到迷失和烦恼(他们必须通过制表符/导航回到他们原来的位置)。 - cvrebert
3个回答

3
根据 Bootstrap文档,您需要指定触发工具提示的方式。可选项有clickhoverfocusmanual,默认情况下是同时启用hoverfocus。因此,只需将 data-trigger="hover" 添加到您的元素即可:
<span data-toggle="tooltip" data-placement="top" data-title="Tooltip" data-trigger="hover">
    <button  data-toggle="modal" data-target="#modal">Toggle</button>
</span>

示例代码:http://jsfiddle.net/6t3kxhLb/1/

1
嗨,你有什么办法可以防止焦点吗? - phuwin
1
@PhuNguyen 你可以先提出一个合适的问题 :) - DavidG

3

这是我使用的解决方案,效果非常好:

$('.modal').on('hidden.bs.modal',function(event){
  event.stopImmediatePropagation();
});

0

在这个话题上我会稍后发表意见。我避免使用Bootstrap的数据属性而是使用Jquery。我通过以下方式实现了这一点...

// Use whatever to trigger the modal, in this case a class
// Get the modal trigger
var modalTriggerObj = $("body").find(".modal-trigger");

modalTriggerObj.on('click', function(e) {
  e.preventDefault();

  // Opens the modal
  $("#modal").modal();
  // Light up the modal trigger with css
  $(this).addClass('modal-on');

  // When the modal hides ...
  $("#modal").on('hide.bs.modal', function() {
    // Return the trigger to its default state
    modalTriggerObj.removeClass('modal-on');
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接