当应用程序内发生某些事件时,我需要动态加载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>
为什么会发生这种情况,又如何在不需要“可重用”模态容器的情况下进行修复?
最佳答案
使用$(“。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>
关于javascript - bootstrap 创建过多的背景,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34666060/