我的页面上有一个模态框,其内容会根据单击两个按钮中的哪一个而发生变化(
<input />
的值会发生变化)。为了更好地添加功能,我设置了一个附加块,如果有错误显示,应该手动打开模态框。
为了确保表单“粘性”,我手动触发相应按钮上的
click
事件等等。但是,当我手动触发 click
事件时,Bootstrap 不会将 .modal-open
添加到正文中。由于我的网站的构建方式,主体上没有 .modal-open
,模态框完全隐藏在其他内容后面。
很明显我做错了什么,但我不知道。这是我的代码的副本:
<?php
$modalerror = false;
$id = 0;
if (/*Basic check for errors*/) {
$modalerror = true;
$id = /*Get the correct id*/;
}
?>
<script type="text/javascript">
jQuery( document ).ready(function($) {
$('#modal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
if (button.attr('data-name') && button.attr('data-name') != '') {
$('#name').val(button.attr('data-name'));
} else {
$('#name').val('');
}
});
});
<?php if ($modalerror) { ?>
jQuery ( window ).load(function() {
jQuery('button[data-id=<?php echo $id; ?>]').trigger('click');
});
<?php } ?>
</script>
经过进一步检查/进展,我注意到我在页面其他地方以完全相同的方式手动触发模态/稍后,将
.modal-open
类添加到正文中没有任何问题。代码示例:
<script type="text/javascript">
function manualOpen(id) {
jQuery('button[data-id="'+id+'"]').trigger('click');
}
</script>
<button type="button" onclick="manualOpen(/*Correct id*/);">Open</button>
甚至更多的测试,我向页面添加了第二个模式,其内容完全不同,在非常特定的情况下自动打开,它不需要加载基于按钮
data-*
属性的自定义内容。如果第二个模态没有某种形式的超时(正如我对此问题的评论中提到的),它也会遇到完全相同的问题。
使用 bootstrap 4,IMO 不使用超时的最佳方法是在模态的关闭事件中添加一个函数。
当一个模态窗口正在关闭,并且在完成关闭操作之前有一个打开另一个模态窗口的命令时,新模态窗口将打开,但类 .modal-open 不会添加到主体中。
下一个函数打开模态,检查是否有打开的模态。新模式将直接打开或在关闭事件回调中打开,具体取决于情况。此功能要求每个模态都有一个 id。
function openModal(modalid) {
//Looks for current modal open
if ($('.modal.fade.show').length > 0) {
//Gets the id of the current opened modal
var currentOpenModalId = $('.modal.fade.show').attr('id');
//Attaches a function to the closing event
$('#' + currentOpenModalId).on('hidden.bs.modal', function () {
//Opens the new model when the closing completes
$('#' + modalid).modal('show');
//Unbinds the callback
$('#' + currentOpenModalId).off('hidden.bs.modal');
});
//Hides the current modal
$('#' + currentOpenModalId).modal('hide');
} else {
//If is not an opened modal, the new modal is opened directly
$('#' + modalid).modal('show');
}
}
我正在使用 bootstap 4.3.1 并修改了“bootstrap.min.js”文件
//bootstrap.min.js (line : 1646)
this._showBackdrop(function () {
g(document.body).removeClass(ce); // ce = 'modal-open'
t._resetAdjustments(),
t._resetScrollbar(),
...
到
//bootstrap.min.js (line : 1646)
this._showBackdrop(function () {
if (document.getElementsByClassName('modal fade show').length == 0) {
g(document.body).removeClass(ce);
}
t._resetAdjustments(),
t._resetScrollbar(),
...
效果很好
我正在使用 Bootstrap 4.1.1 和 jQuery 3.3.1,并面临同样的问题。 50ms并没有解决问题。所以,我必须将其提高到 500 毫秒,结果成功了!
//hide first
$('#modal1').modal('hide');
//add delay when showing next modal
setTimeout(function () {
$('#modal2').modal('show');
}, 500);
仅当第一个模式仍在关闭时第二个模式打开时才会出现此问题。
为了避免出现此问题,请仅在第一个模态完成关闭并触发
hidden.bs.modal
事件后才打开第二个模态。
$("#firstModal").modal("hide");
$("#firstModal").on('hidden.bs.modal', () => {$("#secondModal").modal();});