如何使用" Esc"关闭多模态表格。键盘按钮?

时间:2018-01-16 12:49:28

标签: jquery twitter-bootstrap twitter-bootstrap-3 javascript-events modal-dialog

我发现this question关于如何避免第二个模态的叠加。所以我已经应用了@ A1rPun修复:

$(document).on('show.bs.modal', '.modal', function () {
    var zIndex = 1040 + (10 * $('.modal:visible').length);
    $(this).css('z-index', zIndex);
    setTimeout(function() {
        $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
    }, 0);
});

$(document).on('hidden.bs.modal', '.modal', function () {
    $('.modal:visible').length && $(document.body).addClass('modal-open');
});

现在,当我按下Esc按钮时,后面的模态窗体将关闭。但是,前面的形式是必须关闭的形式。

我试图通过添加一些监听器来解决它,如下面的代码。但如果我这样做,有时两种形式都会同时关闭。也许是因为已经有另一个听众了。

$(document).ready(function() {
    $(window).keydown(function(event){
        if (event.keyCode == 27) {  // Esc code
            if ($('.modal-form').length > 0) {
                let z = 0;
                let modal_to_close = null;
                $('.modal-form').each(function () {
                    let current_z = parseInt($(this).css('z-index'), 10);
                    if (z < current_z) {
                        z = current_z;
                        modal_to_close = $(this);
                    }
                })
                modal_to_close.find('.close').click();
            }
        }
    });
});

我怎样才能使这项工作顺利进行?我应该覆盖Bootstrap keydown侦听器吗?怎么做?

enter image description here

注意:我使用的是Bootstrap v3.3.7

1 个答案:

答案 0 :(得分:1)

例如,您需要在所有模式中使用tabindex="-1"

<div class="modal fade" id="myModal" tabindex="-1">

Working Fiddle