我将处理程序附加到 Bootstrap hidden.bs.modal
事件以检测模式何时关闭,但它可以通过多种方式关闭:
- 通过
$('#modal').modal('hide')
或$('#modal').modal('toggle')
显式关闭它; - 点击模态框的背景部分(如果允许);
- 通过数据属性,例如
data-dismiss="modal"
有没有办法检测使用了哪些选项?在 hidden.bs.modal
处理程序内,e.target
始终显示为 div#modal
最佳答案
问题是 hidden.bs.modal
是一个在模式关闭后触发的事件。所以这不是用户从关闭按钮、 Angular X 或覆盖层触发的 click
事件...
也就是说,您可以使用 click
事件来存储用户在变量中单击的位置以及毫秒后,当 hidden.bs.modal
触发,使用变量。
演示:
$(document).ready(function(){
// Variable to be set on click on the modal... Then used when the modal hidden event fires
var modalClosingMethod = "Programmatically";
// On modal click, determine where the click occurs and set the variable accordingly
$('#exampleModal').on('click', function (e) {
if ($(e.target).parent().attr("data-dismiss")){
modalClosingMethod = "by Corner X";
}
else if ($(e.target).hasClass("btn-secondary")){
modalClosingMethod = "by Close Button";
}
else{
modalClosingMethod = "by Background Overlay";
}
// Restore the variable "default" value
setTimeout(function(){
modalClosingMethod = "Programmatically";
},500);
});
// Modal hidden event fired
$('#exampleModal').on('hidden.bs.modal', function () {
console.log("Modal closed "+modalClosingMethod);
});
// Closing programmatically example
$('#exampleModal').modal("show");
setTimeout(function(){
$('#exampleModal').modal("hide");
},1000);
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" 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">
...
</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>
关于javascript - 如何检测Bootstrap模态关闭方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54282019/