我需要在应用程序中发生某些事件时动态加载HTML片段。其中一些HTML可能是模态对话框。应该没问题,但是在显示时,模态会创建太多的背景。
以下示例说明了此问题(在Google Chrome上进行了测试)。
var html = '<div class="modal fade" tabindex="-1" role="dialog"> ' +
' <div class="modal-dialog"> ' +
' <div class="modal-content"> ' +
' <div class="modal-header"> ' +
' <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> ' +
' <h4 class="modal-title">Modal title</h4> ' +
' </div> ' +
' <div class="modal-body"> ' +
' <p>One fine body…</p> ' +
' </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><!-- /.modal-content --> ' +
' </div><!-- /.modal-dialog --> ' +
'</div><!-- /.modal --> ';
var dlg = $(html).appendTo('body');
setTimeout(function () {
dlg.modal({
//backdrop: false,
keyboard: false
});
}, 1000);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div>Hello</div>
为什么会发生这种情况,如何在不需要“可重复使用”的模态容器的情况下解决这个问题?
答案 0 :(得分:2)
使用$(“。modal”)代替dlg变量来调用模态。
var html = '<div class="modal fade" tabindex="-1" role="dialog"> ' +
' <div class="modal-dialog"> ' +
' <div class="modal-content"> ' +
' <div class="modal-header"> ' +
' <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> ' +
' <h4 class="modal-title">Modal title</h4> ' +
' </div> ' +
' <div class="modal-body"> ' +
' <p>One fine body…</p> ' +
' </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><!-- /.modal-content --> ' +
' </div><!-- /.modal-dialog --> ' +
'</div><!-- /.modal --> ';
$(html).appendTo('body');
setTimeout(function () {
$(".modal").modal({
//backdrop: false,
keyboard: false
});
}, 1000);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div>Hello</div>