多模态叠加

我需要覆盖显示以上的第一个模式,而不是在后面。

Modal overlay behind

$('#openBtn').click(function(){
$('#myModal').modal({show:true})
});
<a data-toggle="modal" href="#myModal" class="btn btn-primary">Launch modal</a>


<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div><div class="container"></div>
<div class="modal-body">
Content for the dialog / modal goes here.
<br>
<br>
<br>
<br>
<br>
<a data-toggle="modal" href="#myModal2" class="btn btn-primary">Launch modal</a>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
</div>
</div>
<div class="modal" id="myModal2" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Second Modal title</h4>
</div><div class="container"></div>
<div class="modal-body">
Content for the dialog / modal goes here.
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
</div>
</div>




<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min.js"></script>

我试图改变.modal-backdropz-index,但它变得一团糟。

在某些情况下,我在同一页上有两个以上的情态动词。

330442 次浏览

尝试在bootply上将以下内容添加到JS中

$('#myModal2').on('show.bs.modal', function () {
$('#myModal').css('z-index', 1030); })


$('#myModal2').on('hidden.bs.modal', function () {
$('#myModal').css('z-index', 1040); })

解释:

在摆弄了属性之后(使用Chrome的开发工具),我已经意识到任何z-index值低于1031将把东西放在背景后面。

因此,通过使用bootstrap的模态事件句柄,我将z-index设置为1030。如果显示#myModal2,如果隐藏#myModal2,则将z-index设置回1040

Demo

注意: 所有答案是"hacks"因为Bootstrap不正式支持多种模式..

"Bootstrap一次只支持一个模式窗口。嵌套的情态动词 不支持,因为我们认为它们的用户体验很差

这里有一些CSS的变通方法/hack…

引导5 beta版(2021年更新)

情态动词的默认z索引再次更改为1060。因此,要覆盖情态动词和背景的使用..

.modal:nth-of-type(even) {
z-index: 1062 !important;
}
.modal-backdrop.show:nth-of-type(even) {
z-index: 1061 !important;
}

https://codeply.com/p/yNgonlFihM


引导4中情态动词的z指数再次更改为1050。因此,要覆盖开放情态动词和背景的使用。

引导4。x(更新2018)

.modal:nth-of-type(even) {
z-index: 1052 !important;
}
.modal-backdrop.show:nth-of-type(even) {
z-index: 1051 !important;
}

https://codeply.com/p/29sH0ofTZb


引导3。x(原答案)

下面是一些使用nth-of-type选择器的CSS,似乎是有效的:

    .modal:nth-of-type(even) {
z-index: 1042 !important;
}
.modal-backdrop.in:nth-of-type(even) {
z-index: 1041 !important;
}

https://codeply.com/p/w8yjOM4DFb

终于解决了。我对它进行了多种测试,效果很好。

这里有一个解决方案,任何人都有同样的问题: 修改Modal.prototype.show函数(在bootstrap.js或modal.js中)

.js

来自:

if (transition) {
that.$element[0].offsetWidth // force reflow
}


that.$element
.addClass('in')
.attr('aria-hidden', false)


that.enforceFocus()

:

if (transition) {
that.$element[0].offsetWidth // force reflow
}


that.$backdrop
.css("z-index", (1030 + (10 * $(".modal.fade.in").length)))


that.$element
.css("z-index", (1040 + (10 * $(".modal.fade.in").length)))
.addClass('in')
.attr('aria-hidden', false)


that.enforceFocus()

这是我发现的最好的方法:检查打开了多少个模态,并将模态和背景的z-index更改为更高的值。

我意识到一个答案已经被接受,但我强烈建议不要破解bootstrap来解决这个问题。

通过连接show .bs.modal和hidden.bs.modal事件处理程序并在那里调整z-index,可以很容易地达到同样的效果。

这是一个工作示例

更多的信息是可用。

这个解决方案自动工作于任意深度的堆栈模态。

脚本源代码:

$(document).ready(function() {


$('.modal').on('hidden.bs.modal', function(event) {
$(this).removeClass( 'fv-modal-stack' );
$('body').data( 'fv_open_modals', $('body').data( 'fv_open_modals' ) - 1 );
});


$('.modal').on('shown.bs.modal', function (event) {
// keep track of the number of open modals
if ( typeof( $('body').data( 'fv_open_modals' ) ) == 'undefined' ) {
$('body').data( 'fv_open_modals', 0 );
}


// if the z-index of this modal has been set, ignore.
if ($(this).hasClass('fv-modal-stack')) {
return;
}


$(this).addClass('fv-modal-stack');
$('body').data('fv_open_modals', $('body').data('fv_open_modals' ) + 1 );
$(this).css('z-index', 1040 + (10 * $('body').data('fv_open_modals' )));
$('.modal-backdrop').not('.fv-modal-stack').css('z-index', 1039 + (10 * $('body').data('fv_open_modals')));
$('.modal-backdrop').not('fv-modal-stack').addClass('fv-modal-stack');


});
});

我也遇到过类似的情况,经过一番思考,我找到了一个解决方案。虽然我不擅长JS,但我还是设法写下了一个小查询。

http://jsfiddle.net/Sherbrow/ThLYb/

<div class="ingredient-item" data-toggle="modal" data-target="#myModal">test1 <p>trerefefef</p></div>
<div class="ingredient-item" data-toggle="modal" data-target="#myModal">tst2 <p>Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum</p></div>
<div class="ingredient-item" data-toggle="modal" data-target="#myModal">test3 <p>afsasfafafsa</p></div>


<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>










$('.ingredient-item').on('click', function(e){


e.preventDefault();


var content = $(this).find('p').text();


$('.modal-body').html(content);


});

根据耶莫·拉默斯的建议,这似乎是一个更短的版本。即使是基本的动画,如淡入/淡出,甚至疯狂的蝙蝠侠报纸旋转。http://jsfiddle.net/ketwaroo/mXy3E/

$('.modal').on('show.bs.modal', function(event) {
var idx = $('.modal:visible').length;
$(this).css('z-index', 1040 + (10 * idx));
});
$('.modal').on('shown.bs.modal', function(event) {
var idx = ($('.modal:visible').length) -1; // raise backdrop after animation.
$('.modal-backdrop').not('.stacked').css('z-index', 1039 + (10 * idx));
$('.modal-backdrop').not('.stacked').addClass('stacked');
});

在modal.js中添加全局变量

var modalBGIndex = 1040; // modal backdrop background
var modalConIndex = 1042; // modal container data

//添加变量modal .prototype. background

var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })


modalConIndex = modalConIndex + 2; // add this line inside "Modal.prototype.show"


that.$element
.show()
.scrollTop(0)
that.$element.css('z-index',modalConIndex) // add this line after show modal


if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate


modalBGIndex = modalBGIndex + 2; // add this line increase modal background index 2+


this.$backdrop.addClass('in')
this.$backdrop.css('z-index',modalBGIndex) // add this line after backdrop addclass

解决方案灵感来自@YermoLamers &@Ketwaroo。

< p > 背景z指数修正
此解决方案使用setTimeout,因为事件show.bs.modal触发时不会创建.modal-backdrop
$(document).on('show.bs.modal', '.modal', function() {
const zIndex = 1040 + 10 * $('.modal:visible').length;
$(this).css('z-index', zIndex);
setTimeout(() => $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack'));
});
  • 这适用于页面上创建的每个.modal(即使是动态模态)
  • 背景瞬间覆盖了之前的模式

使用实例

< p > z - index
如果你不喜欢硬编码的z-index,你可以这样计算页面上的最高z-index:

const zIndex = 10 +
Math.max(...Array.from(document.querySelectorAll('*')).map((el) => +el.style.zIndex));
< p > 滚动条修正
如果页面上的某个模态超出了浏览器的高度,那么关闭第二个模态时就不能在其中滚动。要修复此问题,添加:

$(document).on('hidden.bs.modal', '.modal',
() => $('.modal:visible').length && $(document.body).addClass('modal-open'));
< p > 版本
这个解决方案是用bootstrap 3.1.0 - 3.3.5

测试的

每次你运行sys。showModal函数增加z-index并将其设置为新的模态。

function system() {


this.modalIndex = 2000;


this.showModal = function (selector) {
this.modalIndex++;


$(selector).modal({
backdrop: 'static',
keyboard: true
});
$(selector).modal('show');
$(selector).css('z-index', this.modalIndex );
}


}


var sys = new system();


sys.showModal('#myModal1');
sys.showModal('#myModal2');

结合A1rPun的回答和StriplingWarrior的建议,我想到了这个:

$(document).on({
'show.bs.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);
},
'hidden.bs.modal': function() {
if ($('.modal:visible').length > 0) {
// restore the modal-open class to the body element, so that scrolling works
// properly after de-stacking a modal.
setTimeout(function() {
$(document.body).addClass('modal-open');
}, 0);
}
}
}, '.modal');

工作甚至动态模态添加后,并消除了第二个滚动条的问题。最值得注意的是,我发现这个功能很有用,它将模态中的表单与Bootbox警报的验证反馈集成在一起,因为这些使用动态模态,因此需要将事件绑定到document,而不是.modal,因为这只会将它附加到现有的模态。

这里

在解决堆叠情态动词关闭时滚动主页面时,我发现Bootstrap的新版本(至少从3.0.3版本开始)不需要任何额外的代码来堆栈模态。

您可以向页面添加多个模态(当然有不同的ID)。当打开多个模式时发现的唯一问题是关闭一个模式会删除主体选择器的modal-open类。

你可以使用下面的Javascript代码重新添加modal-open:

$('.modal').on('hidden.bs.modal', function (e) {
if($('.modal').hasClass('in')) {
$('body').addClass('modal-open');
}
});

在不需要背景效果的情况下,你可以设置data-backdrop="false"

3.1.1版本。固定修复模式背景覆盖模式的滚动条,但上述解决方案似乎也适用于较早的版本。

每个模态都应该有一个不同的id,每个链接都应该指向不同的模态id。所以应该是这样的:

<a href="#myModal" data-toggle="modal">
...
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
...
<a href="#myModal2" data-toggle="modal">
...
<div id="myModal2" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
...

其他的解决方案在开箱即用时对我不起作用。我想可能是因为我使用的是Bootstrap(3.3.2)的最新版本....覆盖正在出现在…之上模态对话框。

我重构了一些代码,并注释掉了调整模式背景的部分。这解决了问题。

    var $body = $('body');
var OPEN_MODALS_COUNT = 'fv_open_modals';
var Z_ADJUSTED = 'fv-modal-stack';
var defaultBootstrapModalZindex = 1040;


// keep track of the number of open modals
if ($body.data(OPEN_MODALS_COUNT) === undefined) {
$body.data(OPEN_MODALS_COUNT, 0);
}


$body.on('show.bs.modal', '.modal', function (event)
{
if (!$(this).hasClass(Z_ADJUSTED))  // only if z-index not already set
{
// Increment count & mark as being adjusted
$body.data(OPEN_MODALS_COUNT, $body.data(OPEN_MODALS_COUNT) + 1);
$(this).addClass(Z_ADJUSTED);


// Set Z-Index
$(this).css('z-index', defaultBootstrapModalZindex + (1 * $body.data(OPEN_MODALS_COUNT)));


//// BackDrop z-index   (Doesn't seem to be necessary with Bootstrap 3.3.2 ...)
//$('.modal-backdrop').not( '.' + Z_ADJUSTED )
//        .css('z-index', 1039 + (10 * $body.data(OPEN_MODALS_COUNT)))
//        .addClass(Z_ADJUSTED);
}
});
$body.on('hidden.bs.modal', '.modal', function (event)
{
// Decrement count & remove adjusted class
$body.data(OPEN_MODALS_COUNT, $body.data(OPEN_MODALS_COUNT) - 1);
$(this).removeClass(Z_ADJUSTED);
// Fix issue with scrollbar being shown when any modal is hidden
if($body.data(OPEN_MODALS_COUNT) > 0)
$body.addClass('modal-open');
});

顺便说一句,如果你想在AngularJs中使用它,只需将代码放在模块的.run()方法中即可。

编辑:Bootstrap 3.3.4已经解决了这个问题(和其他模式问题),所以如果你可以更新你的Bootstrap CSS和JS,这将是最好的解决方案。如果你不能更新下面的解决方案仍然可以工作,基本上做同样的事情,bootstrap 3.3.4(重新计算和应用填充)。

Bass Jobsen指出,Bootstrap的新版本已经解决了z指数问题。模态开放类和填充右仍然是我的问题,但这个脚本的灵感来自Yermo Lamers解决方案解决了它。只要把它放到JS文件中就可以了。

$(document).on('hide.bs.modal', '.modal', function (event) {
var padding_right = 0;
$.each($('.modal'), function(){
if($(this).hasClass('in') && $(this).modal().data('bs.modal').scrollbarWidth > padding_right) {
padding_right = $(this).modal().data('bs.modal').scrollbarWidth
}
});
$('body').data('padding_right', padding_right + 'px');
});


$(document).on('hidden.bs.modal', '.modal', function (event) {
$('body').data('open_modals', $('body').data('open_modals') - 1);
if($('body').data('open_modals') > 0) {
$('body').addClass('modal-open');
$('body').css('padding-right', $('body').data('padding_right'));
}
});


$(document).on('shown.bs.modal', '.modal', function (event) {
if (typeof($('body').data('open_modals')) == 'undefined') {
$('body').data('open_modals', 0);
}
$('body').data('open_modals', $('body').data('open_modals') + 1);
$('body').css('padding-right', (parseInt($('body').css('padding-right')) / $('body').data('open_modals') + 'px'));
});

对我来说,解决这个问题的方法是不要在我的modal div上使用“fade”类。

适用于开启/关闭多种模式

jQuery(function()
{
jQuery(document).on('show.bs.modal', '.modal', function()
{
var maxZ = parseInt(jQuery('.modal-backdrop').css('z-index')) || 1040;


jQuery('.modal:visible').each(function()
{
maxZ = Math.max(parseInt(jQuery(this).css('z-index')), maxZ);
});


jQuery('.modal-backdrop').css('z-index', maxZ);
jQuery(this).css("z-index", maxZ + 1);
jQuery('.modal-dialog', this).css("z-index", maxZ + 2);
});


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


var maxZ = 1040;


jQuery('.modal:visible').each(function()
{
maxZ = Math.max(parseInt(jQuery(this).css('z-index')), maxZ);
});


jQuery('.modal-backdrop').css('z-index', maxZ-1);
}
});
});

演示

https://www.bootply.com/cObcYInvpq#

不幸的是,我没有评论的声誉,但应该注意的是,采用硬编码基准1040 z-index的公认解决方案似乎优于试图找到在页面上呈现的最大zIndex计算。

似乎某些扩展/插件依赖于顶级DOM内容,这使得. max计算如此大,以至于它不能再增加zIndex。这会导致一个模态,其中覆盖出现在模态不正确(如果你使用Firebug/谷歌检查器工具,你会看到一个zIndex在2^n - 1的顺序)

我一直无法分离出数学的各种形式的具体原因是什么。z-Index的Max会导致这种情况,但它可能会发生,而且它对少数用户来说是独特的。(我在browserstack上的一般测试让这段代码完美地工作)。

希望这能帮助到一些人。

我创建了一个Bootstrap插件,它包含了这里发布的很多想法。

Bootply上的演示:http://www.bootply.com/cObcYInvpq

Github: https://github.com/jhaygt/bootstrap-multimodal

它还解决了连续情态动词导致背景变得越来越暗的问题。这确保在任何给定的时间只有一个背景可见:

if(modalIndex > 0)
$('.modal-backdrop').not(':first').addClass('hidden');

可见背景的z-index在show.bs.modalhidden.bs.modal事件中都被更新:

$('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (modalIndex * 20));

在我的情况下,问题是由一个浏览器扩展引起的,它包括bootstrap.js文件,其中show事件处理了两次,并添加了两个modal-backdrop div,但关闭模式时,只有一个被删除。

发现通过在chrome中的body元素中添加子树修改断点,并跟踪添加modal-backdrop div。

$(window).scroll(function(){
if($('.modal.in').length && !$('body').hasClass('modal-open'))
{
$('body').addClass('modal-open');
}


});

看看这个!这个解决方案解决了我的问题,几个简单的CSS行:

.modal:nth-of-type(even) {
z-index: 1042 !important;
}
.modal-backdrop.in:nth-of-type(even) {
z-index: 1041 !important;
}

这是我找到它的地方的链接:Bootply 只要确保需要出现在顶部的.modual是HTML代码中的第二,这样CSS就可以发现它是“偶数”

没有脚本解决方案,只使用css给你有两层情态,设置第2个情态为更高的z索引

.second-modal { z-index: 1070 }


div.modal-backdrop + div.modal-backdrop {
z-index: 1060;
}

如果你正在寻找Bootstrap 4的解决方案,有一个简单的使用纯CSS:

.modal.fade {
background: rgba(0,0,0,0.5);
}

更新:22.01.2019,13.41 我通过jhay优化了解决方案,它还支持关闭和打开相同或不同的对话框,例如,从一个细节数据向前或向后步进到另一个细节数据

(function ($, window) {
'use strict';


var MultiModal = function (element) {
this.$element = $(element);
this.modalIndex = 0;
};


MultiModal.BASE_ZINDEX = 1040;


/* Max index number. When reached just collate the zIndexes */
MultiModal.MAX_INDEX = 5;


MultiModal.prototype.show = function (target) {
var that = this;
var $target = $(target);


// Bootstrap triggers the show event at the beginning of the show function and before
// the modal backdrop element has been created. The timeout here allows the modal
// show function to complete, after which the modal backdrop will have been created
// and appended to the DOM.


// we only want one backdrop; hide any extras
setTimeout(function () {
/* Count the number of triggered modal dialogs */
that.modalIndex++;


if (that.modalIndex >= MultiModal.MAX_INDEX) {
/* Collate the zIndexes of every open modal dialog according to its order */
that.collateZIndex();
}


/* Modify the zIndex */
$target.css('z-index', MultiModal.BASE_ZINDEX + (that.modalIndex * 20) + 10);


/* we only want one backdrop; hide any extras */
if (that.modalIndex > 1)
$('.modal-backdrop').not(':first').addClass('hidden');


that.adjustBackdrop();
});


};


MultiModal.prototype.hidden = function (target) {
this.modalIndex--;
this.adjustBackdrop();


if ($('.modal.in').length === 1) {


/* Reset the index to 1 when only one modal dialog is open */
this.modalIndex = 1;
$('.modal.in').css('z-index', MultiModal.BASE_ZINDEX + 10);
var $modalBackdrop = $('.modal-backdrop:first');
$modalBackdrop.removeClass('hidden');
$modalBackdrop.css('z-index', MultiModal.BASE_ZINDEX);


}
};


MultiModal.prototype.adjustBackdrop = function () {
$('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (this.modalIndex * 20));
};


MultiModal.prototype.collateZIndex = function () {


var index = 1;
var $modals = $('.modal.in').toArray();




$modals.sort(function(x, y)
{
return (Number(x.style.zIndex) - Number(y.style.zIndex));
});


for (i = 0; i < $modals.length; i++)
{
$($modals[i]).css('z-index', MultiModal.BASE_ZINDEX + (index * 20) + 10);
index++;
};


this.modalIndex = index;
this.adjustBackdrop();


};


function Plugin(method, target) {
return this.each(function () {
var $this = $(this);
var data = $this.data('multi-modal-plugin');


if (!data)
$this.data('multi-modal-plugin', (data = new MultiModal(this)));


if (method)
data[method](target);
});
}


$.fn.multiModal = Plugin;
$.fn.multiModal.Constructor = MultiModal;


$(document).on('show.bs.modal', function (e) {
$(document).multiModal('show', e.target);
});


$(document).on('hidden.bs.modal', function (e) {
$(document).multiModal('hidden', e.target);
});}(jQuery, window));

对我来说,这些简单的scss规则非常有效:

.modal.show{
z-index: 1041;
~ .modal.show{
z-index: 1043;
}
}
.modal-backdrop.show {
z-index: 1040;
+ .modal-backdrop.show{
z-index: 1042;
}
}

如果这些规则导致错误的模态在你的情况下,要么改变你的模态div的顺序,或者在上面的scss中改变(奇数)为(偶数)。

如果你想让一个特定的模态出现在另一个开放模态的顶部,尝试添加最顶层模态的HTML和另一个模态div

这招对我很管用:

<div id="modal-under" class="modal fade" ... />


<!--
This modal-upper should appear on top of #modal-under when both are open.
Place its HTML after #modal-under. -->
<div id="modal-upper" class="modal fade" ... />

我的解决方案自举4,与无限深度的模态和动态模态工作。

$('.modal').on('show.bs.modal', function () {
var $modal = $(this);
var baseZIndex = 1050;
var modalZIndex = baseZIndex + ($('.modal.show').length * 20);
var backdropZIndex = modalZIndex - 10;
$modal.css('z-index', modalZIndex).css('overflow', 'auto');
$('.modal-backdrop.show:last').css('z-index', backdropZIndex);
});
$('.modal').on('shown.bs.modal', function () {
var baseBackdropZIndex = 1040;
$('.modal-backdrop.show').each(function (i) {
$(this).css('z-index', baseBackdropZIndex + (i * 20));
});
});
$('.modal').on('hide.bs.modal', function () {
var $modal = $(this);
$modal.css('z-index', '');
});

检查情态动词的计数,并将值添加到背景作为z-index

    var zIndex = 1500 + ($('.modal').length*2) + 1;
this.popsr.css({'z-index': zIndex});


this.popsr.on('shown.bs.modal', function () {
$(this).next('.modal-backdrop').css('z-index', zIndex - 1);
});


this.popsr.modal('show');

这段代码非常适合用于引导4。其他代码中的问题是如何选择模态背景。这将是更好的,如果你使用jQuery的下一个选择在实际的模态已经显示。

$(document).on('show.bs.modal', '.modal', function () {
var zIndex = 1040 + (10 * $('.modal').length);
var model = $(this);
model.css('z-index', zIndex);
model.attr('data-z-index', zIndex);
});


$(document).on('shown.bs.modal', '.modal', function () {
var model = $(this);
var zIndex = model.attr('data-z-index');
model.next('.modal-backdrop.show').css('z-index', zIndex - 1);
  

});

Bootstrap 4.5的简单解决方案

.modal.fade {
background: rgba(0, 0, 0, 0.5);
}


.modal-backdrop.fade {
opacity: 0;
}

这是一个非常古老的威胁,但是,对我来说,只是工作移动模式的html代码,我想在前面的第一个地方的文件。

A1rPun的答案在一个小的修改后完美地工作(Bootstrap 4.6.0)。我的名声不允许我评论,所以我会在网上回复。

我只是为.modal.show替换了每个.modal:visible

因此,在打开多个情态动词时修复背景:

$(document).on('show.bs.modal', '.modal', function () {
var zIndex = 1040 + (10 * $('.modal.show').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.show').length && $(document.body).addClass('modal-open');
});

基于这个答案的示例小提琴,我更新了它以支持引导3和4,并修复了注释中提到的所有问题。因为我也注意到它们,因为我有一些模态有一个超时和自动关闭。

它将不能与bootstrap 5一起工作。引导5不再使用node.data('bs.modal')存储bs.modal对象。

我建议全屏查看代码片段。

使用与前面提到的答案相同的例子引导3,只是对话4被修改了。

!function () {
var z = "bs.modal.z-index.base",
re_sort = function (el) {
Array.prototype.slice.call($('.modal.show,.modal.in').not(el))
.sort(function (a, b) { // sort by z-index lowest to highest
return +a.style.zIndex - +b.style.zIndex
})
.forEach(function (el, idx) { // re-set the z-index based on the idx
el.style.zIndex = $(el).data(z) + (2 * idx);
const b = $(el).data('bs.modal')._backdrop || $(el).data("bs.modal").$backdrop;
if (b) {
$(b).css("z-index", +el.style.zIndex - 1);
}
});
};
$(document).on('show.bs.modal', '.modal', function (e) {
// removing the currently set zIndex if any
this.style.zIndex = '';




/*
* should be 1050 always, if getComputedStyle is not supported use 1032 as variable...
*
* see https://getbootstrap.com/docs/4.0/layout/overview/#z-index and adjust the
* other values to higher ones, if required
*
* Bootstrap 3: https:////netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.css
.modal {
[...]
z-index: 1050;
[...]
}
.modal-backdrop {
[...]
z-index: 1040;
[...]
}
* Bootstrap 4: https://getbootstrap.com/docs/4.0/layout/overview/#z-index
*
*
* lowest value which doesn't interfer with other bootstrap elements
* since we manipulate the z-index of the backdrops too we need two for each modal
* using 1032 you could open up to 13 modals without overlapping popovers
*/


if (!$(this).data(z)) {
let def = +getComputedStyle(this).zIndex; // 1050 by default
def = 1032;
$(this).data(z, def);
}


// resort all others, except this
re_sort(this);


// 2 is fine 1 layer for the modal, 1 layer for the backdrop
var zIndex = $(this).data(z) + (2 * $('.modal.show,.modal.in').not(this).length);
e.target.style.zIndex = zIndex;


/*
* Bootstrap itself stores the var using jQuery data property the backdrop
* is present there, even if it may not be attached to the DOM
*
* If it is not present, wait for it, using requestAnimationFrame loop
*/
const waitForBackdrop = function () {
try { // can fail to get the config if the modal is opened for the first time
const config = $(this).data('bs.modal')._config || $(this).data('bs.modal').options;
if (config.backdrop != false) {
const node = $(this).data('bs.modal')._backdrop ||
$(this).data("bs.modal").$backdrop;
if (node) {
$(node).css('z-index', +this.style.zIndex - 1);
} else {
window.requestAnimationFrame(waitForBackdrop);
}
}
} catch (e) {
window.requestAnimationFrame(waitForBackdrop);
}
}.bind(this);
waitForBackdrop();
});
$(document).on("shown.bs.modal", ".modal", function () {
re_sort();
});


$(document).on('hidden.bs.modal', '.modal', function (event) {
this.style.zIndex = ''; // when hidden, remove the z-index
if (this.isConnected) {
const b = $(this).data('bs.modal')._backdrop || $(this).data("bs.modal").$backdrop;
if (b) {
$(b).css("z-index", '');
}
}
re_sort();
// if still backdrops are present at dom - readd modal-open
if ($('.modal-backdrop.show,.modal-backdrop.in').length)
$(document.body).addClass("modal-open");
})
}();
/* crazy batman newspaper spinny thing */
.rotate {
transform:rotate(180deg);
transition:all 0.25s;
}
.rotate.in {
transform:rotate(1800deg);
transition:all 0.75s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet"/>




<h2>Stacked Bootstrap Modal Example.</h2>
<a data-toggle="modal" href="#myModal" class="btn btn-primary">Launch modal</a>


<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal 1</h4>


</div>
<div class="container"></div>
<div class="modal-body">Content for the dialog / modal goes here.
<br>
<br>
<br>
<p>more content</p>
<br>
<br>
<br> <a data-toggle="modal" href="#myModal2" class="btn btn-primary">Launch modal</a>


</div>
<div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>


</div>
</div>
</div>
</div>
<div class="modal fade rotate" id="myModal2">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal 2</h4>


</div>
<div class="container"></div>
<div class="modal-body">Content for the dialog / modal goes here.
<br>
<br>
<p>come content</p>
<br>
<br>
<br> <a data-toggle="modal" href="#myModal3" class="btn btn-primary">Launch modal</a>


</div>
<div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>


</div>
</div>
</div>
</div>
<div class="modal fade" id="myModal3">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal 3</h4>


</div>
<div class="container"></div>
<div class="modal-body">Content for the dialog / modal goes here.
<br>
<br>
<br>
<br>
<br> <a data-toggle="modal" href="#myModal4" class="btn btn-primary">Launch modal</a>


</div>
<div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>


</div>
</div>
</div>
</div>
<div class="modal fade" id="myModal4">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal 4</h4>
</div>
<div class="container"></div>
<div class="modal-body">
<button onclick="$('#myModal').modal('hide');" class="btn btn-primary">hide #1</button>
<button onclick="$('#myModal').modal('show');" class="btn btn-primary">show #1</button>
<br>
<button onclick="$('#myModal2').modal('hide');" class="btn btn-primary">hide #2</button>
<button onclick="$('#myModal2').modal('show');" class="btn btn-primary">show #2</button>
<br>
<button onclick="$('#myModal3').modal('hide');" class="btn btn-primary">hide #3</button>
<button onclick="$('#myModal3').modal('show');" class="btn btn-primary">show #3</button>
</div>
<div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>


</div>
</div>
</div>
</div>

引导程序4(请参阅引导程序3片段以获得注释代码)

!function () {
var z = "bs.modal.z-index.base",
re_sort = function (el) {
Array.prototype.slice.call($('.modal.show,.modal.in').not(el))
.sort(function (a, b) {
return +a.style.zIndex - +b.style.zIndex
})
.forEach(function (el, idx) {
el.style.zIndex = $(el).data(z) + (2 * idx);
const b = $(el).data('bs.modal')._backdrop || $(el).data("bs.modal").$backdrop;
if (b) {
$(b).css("z-index", +el.style.zIndex - 1);
}
});
};
$(document).on('show.bs.modal', '.modal', function (e) {
this.style.zIndex = '';
if (!$(this).data(z)) {
let def = +getComputedStyle(this).zIndex;
def = 1032;
$(this).data(z, def);
}
re_sort(this);
var zIndex = $(this).data(z) + (2 * $('.modal.show,.modal.in').not(this).length);
e.target.style.zIndex = zIndex;


const waitForBackdrop = function () {
try {
const config = $(this).data('bs.modal')._config || $(this).data('bs.modal').options;
if (config.backdrop != false) {
const node = $(this).data('bs.modal')._backdrop ||
$(this).data("bs.modal").$backdrop;
if (node) {
$(node).css('z-index', +this.style.zIndex - 1);
} else {
window.requestAnimationFrame(waitForBackdrop);
}
}
} catch (e) {
window.requestAnimationFrame(waitForBackdrop);
}
}.bind(this);
waitForBackdrop();
});
$(document).on("shown.bs.modal", ".modal", function () {
re_sort();
});


$(document).on('hidden.bs.modal', '.modal', function (event) {
this.style.zIndex = '';
if (this.isConnected) {
const b = $(this).data('bs.modal')._backdrop || $(this).data("bs.modal").$backdrop;
if (b) {
$(b).css("z-index", '');
}
}
re_sort();
if ($('.modal-backdrop.show,.modal-backdrop.in').length)
$(document.body).addClass("modal-open");
})
}();




// creates dynamic modals i used this for stuff like
// `enterSomething('stuff','to','display').then(...)`
!function() {
let a = (i, a) => Array.prototype.forEach.call(a, (e) => $('#' + i + '-modal').find('.modal-body').append(e)),
b = function () { $(this).remove() },
c = (i, a) => Array.prototype.forEach.call(a, (e) => $('#' + i + '-modal-text-container').append(e)),
r = () => 'dialog-' + (Date.now() + '-' + Math.random()).replace('.', '-');
this.createModal = function createModal() {
let id = r();
$(document.body).append('<div class="modal fade" tabindex="-1" role="dialog" data-backdrop="static" aria-hidden="true" id="' + id + '-modal"><div class="modal-dialog d-flex modal-xl"><div class="modal-content align-self-stretch" style="overflow: hidden; max-height: -webkit-fill-available;"><div class="modal-header py-1"><h5 class="modal-header-text p-0 m-0"></h5><button id="' + id + '-modal-btn-close" type="button" tabindex="-1" class="close" data-dismiss="modal" aria-label="Close" title="Close"><span aria-hidden="true">&times;</span></button></div><div class="modal-body py-2"></div><div class="modal-footer py-1"><button type="button" class="btn btn-primary btn-sm" id="' + id + '-modal-btn-ok">Okay</button></div></div></div></div>');
$('#' + id + '-modal-btn-ok').on('click', () => $('#' + id + '-modal').modal('hide'));
$('#' + id + '-modal').on('shown.bs.modal', () => $('#' + id + '-modal-btn-ok').focus()).on('hidden.bs.modal', b).modal('show');
$('#' + id + '-modal').find(".modal-header-text").html("Title");
a(id, arguments);
return new Promise((r) => $('#' + id + '-modal').on('hide.bs.modal', () => r()));
}
}();
function another() {
createModal(
$("<button class='btn mx-1'>Another...</button>").on("click", another),
$("<button class='btn mx-1'>Close lowest</button>").on("click", closeLowest),
$("<button class='btn mx-1'>Bring lowest to front</button>").on("click", lowestToFront),
$("<p>").text($(".modal.show,.modal.in").length)
).then(() => console.log("modal closed"));
// only for this example:
$(".modal").last().css('padding-top', ($(".modal.show,.modal.in").length * 20) +'px');
}
function closeLowest() {
$(Array.prototype.slice.call($('.modal.show,.modal.in'))
.sort(function (a, b) { // sort by z-index lowest to highest
return +a.style.zIndex - +b.style.zIndex
})).first().modal('hide');
}
function lowestToFront() {
$(Array.prototype.slice.call($('.modal.show,.modal.in'))
.sort(function (a, b) { // sort by z-index lowest to highest
return +a.style.zIndex - +b.style.zIndex
})).first().trigger('show.bs.modal');
}
another();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<p>Use inspecter to check z-index values</p>


<button class="btn btn-outline-primary" onclick="another()">Click!</button>

z-indexmodal-backdrop更正css

.modal.fade {
z-index: 10000000 !important;
background: rgba(0, 0, 0, 0.5);
}
.modal-backdrop.fade {
opacity: 0;
}

Bootstrap 5的解决方案(纯JS)。

@A1rPun的答案启发的解决方案。

// On modal open
document.addEventListener('show.bs.modal', function(e) {


// Get count of opened modals
let modalsCount = 1;
document.querySelectorAll('.modal').forEach(function(modalElement) {
if (modalElement.style.display == 'block') {
modalsCount++;
}
});


// Set modal and backdrop z-indexes
const zIndex = 1055 + 10 * modalsCount;
e.target.style.zIndex = zIndex;
setTimeout(() => {
const backdropNotStacked = document.querySelector('.modal-backdrop:not(.modal-stack)');
backdropNotStacked.style.zIndex = ('z-index', zIndex - 5);
backdropNotStacked.classList.add('modal-stack');
});


});

解释

  1. 循环所有可见的modal(你不能使用pseudoselector :可见,这只在jquery中)
  2. 计算新的z指数。Bootstrap 5的默认值是1055,因此:

默认值(1055)+ 10 *打开的模态数

  1. 将这个新的计算z-index设置为模态
  2. 识别背景(背景没有指定类-在本例中为.modal-stack)
  3. 设置这个新的计算z-index -5为背景
  4. 添加类.modal-stack到背景,以防止在打开下一个模式时得到这个背景