我已经直接从Bootstrap示例中使用了我的模态代码,并且只包括Bootstrap .js(而不是Bootstrap -modal.js)。但是,我的模态出现在灰色渐隐(背景)下面,是不可编辑的。
这是它的样子:
这是重现这个问题的一种方法。该代码的基本结构是这样的:
<body>
<p>Lorem ipsum dolor sit amet.</p>
<div class="my-module">
This container contains the modal code.
<div class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">Modal</div>
</div>
</div>
</div>
</div>
</body>
body {
padding-top: 50px;
}
.my-module {
position: fixed;
top: 0;
left: 0;
}
你知道为什么会这样吗或者我能做些什么来弥补吗?
在附加到主体时要小心!
这肯定会从背景后面得到那个模态:
$('#myModal').appendTo("body").modal('show');
然而,这将在每次打开主体时添加另一个模态,这可能会导致在更新面板中添加具有编辑和更新的网格视图等控件到模态时头痛。因此,你可以考虑在模式关闭时删除它:
例如:
$(document).on('hidden.bs.modal', function () {
$('.modal').remove();
});
将删除添加的模态。(当然,这是一个例子,你可能想要使用另一个你添加到模态的类名)。
正如其他人已经说过的;你可以简单地从模式中关闭back-drop (data- background ="false"),或者如果你不能没有屏幕变暗,你可以调整.modal- backstage CSS类(或者增加z-index)。
更新:原来的JS方法导致了我的模态的多个克隆
如果组件被初始化多次,则附加到主体。相反,首先确认模式不是
已经添加:
function AttachModalsToBody(modalID) {
var modal = $("body").children('#' + modalID);
if ($("body").children('#' + modalID).length == 0) {
$('#' + modalID).appendTo("body");
}
}
在Blazor(在那里我使用Bootstrap 5.0),我做了以下(改编自@AdamAlbright的回答),以防止模式出现在背景后面:
在我的项目中,每个模态都在自己独立的组件中,因为我需要从其他组件中设置它们的参数,显然不可能将模态移动到这些父组件之外。因此,当它第一次呈现时,我使用JS Interop将每个模态附加到主体。
例如:MyModal.razor
在每个模态/组件内部:
@inject IJSRuntime jsRuntime
<!--HTML Section omitted for brevity-->
@code{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
await jsRuntime.InvokeVoidAsync("AttachModalToBody", "#myModalID");
}
}
在JS文件中:
function AttachModalToBody(modalID) {
$(modalID).appendTo("body");
}