How can I unfocus the modal trigger button after closing the modal in bootstrap

[亡魂溺海] 提交于 2019-11-30 13:08:44

The focus back to the trigger element is set within the modal plugin using a .one() binding, which unfortunately cannot be unbound. The good news is we can do this:

$('#myModal').on('shown.bs.modal', function(e){
    $('#myModaltrigger').one('focus', function(e){$(this).blur();});
});

Where #myModaltrigger is the ID of the modal trigger button. The reason to use the .one() binding is so that the function to blur will be called only after the modal is shown. Once it hides, and the focus/blur happens, the button can be focused normally, like by tabbing to it, without it automatically blurring.

See this working example

Indeed, @cvrebert is right here that doing this negatively impacts accessibility.

blur() resets the focus, so keyboard users (both sighted keyboard users, and more critically users of screenreaders) are effectively bounced back to the very start of the page.

try http://jsbin.com/sukevefepo/1/ just using the keyboard: TAB to the button, trigger it with ENTER/SPACE, then TAB to the close button, ENTER/SPACE. now, after the modal is closed, TAB...and you see that your focus is back on the very first link. for anything but the most simple pages, this is a major annoyance at best, and can be dramatically disorienting for screenreader users).

in short: current Bootstrap behaviour is correct. I understand the desire to neuter the focused appearance of the modal trigger once the modal itself is closed...but using blur() is not the answer (unless you care little about keyboard/AT users, that is).

a more robust approach, that I'm planning to investigate for future version of Bootstrap, is to dynamically set a class on the body once a user first navigates using TAB/SHIFT+TAB (indicating a keyboard user), and to suppress :focus styles for these situations otherwise.

My solution which works with multiple modals on page (based on Bootstrap modal examples):

$('.modal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // Button that triggered the modal
    button.one('focus', function (event) {
        $(this).blur();
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!