点击外部时如何防止 Bootstrap 模态关闭
答案:使用模态的backdrop
选项
默认情况下,如果您在 Bootstrap 模态窗口之外单击,即在背景或黑暗区域上单击,它将关闭并消失。 当您在模态框内并按键盘上的退出键时,也会发生这种情况。 但是您可以通过将模态的 backdrop
选项设置为 static
并将 keyboard
选项设置为 false
来防止这种情况发生,如下例所示:
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>禁止关闭 Bootstrap 模态</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery-3.5.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$(".show-modal").click(function(){
$("#myModal").modal({
backdrop: 'static',
keyboard: false
});
});
});
</script>
</head>
<body>
<!-- 按钮 HTML (触发模态) -->
<input type="button" class="btn btn-lg btn-primary show-modal" value="Show Demo Modal">
<!-- 模态 HTML -->
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Confirmation</h5>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>Do you want to save changes you made to document before closing?</p>
<p class="text-warning"><small>If you don't save, your changes will be lost.</small></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>
</div>
</div>
</body>
</html>
FAQ 相关问题解答
以下是与此主题相关的更多常见问题解答: