Bootstrap Modal 是 Bootstrap 框架中的一个组件,用于创建模态框(弹出窗口)。模态框通常用于显示额外的信息、警告、确认对话框等,而不离开当前页面。
Bootstrap Modal 主要有以下几种类型:
假设你已经有一个 Bootstrap Modal,并且希望在某个函数执行时关闭它。
你可以使用纯 JavaScript 来关闭 Bootstrap Modal。以下是一个示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Close Bootstrap Modal with JavaScript</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Modal body text goes here.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<button onclick="closeModal()" class="btn btn-primary">Close Modal</button>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
function closeModal() {
var modal = document.getElementById('myModal');
if (modal) {
$(modal).modal('hide');
}
}
</script>
</body>
</html>
myModal
。closeModal
函数,通过 jQuery 选择器找到模态框并调用 modal('hide')
方法来关闭它。通过这种方式,你可以在执行某个函数时关闭 Bootstrap Modal,而不需要依赖 jQuery。
领取专属 10元无门槛券
手把手带您无忧上云