如何使用 "Esc" 键盘按钮关闭多模态表单?
How to close multi modal forms right with the "Esc" keyboard button?
我发现 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 侦听器吗?怎么做?
注意:我正在使用Bootstrap v3.3.7
例如,您需要在所有模态上使用 tabindex="-1"
。
<div class="modal fade" id="myModal" tabindex="-1">
我发现 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 侦听器吗?怎么做?
注意:我正在使用Bootstrap v3.3.7
例如,您需要在所有模态上使用 tabindex="-1"
。
<div class="modal fade" id="myModal" tabindex="-1">