当用户尝试刷新或离开页面时,如何打开Bootstrap模式?模态应显示为:““确定要离开此页面吗? ”
我正在关注代码:
window.onbeforeunload = function() {
$('#myModal').modal("show");
return "Data will be lost if you leave the page, are you sure?";
};
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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">
Are you sure you want to navigate away from this page?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">No I want to stay</button>
<button type="button" class="btn btn-primary">Yes, I'm sure</button>
</div>
</div>
</div>
</div>
但是使用此代码段,模式会打开,但页面仍会刷新。
答案 0 :(得分:1)
当用户尝试离开时,将触发unload事件。但是,如果将DIV用作弹出窗口,则浏览器将在用户有机会阅读它之前导航离开。 要使其保持在那里,您必须使用警报/提示/确认对话框。
绑定到html对我来说效果很好,而不是卸载。
完整参考:https://stackoverflow.com/a/30603477/1081909
$("html").bind("mouseleave", function () {
$('#myModal').modal("show");
$("#okButton").click(function(){
location.reload();
});
//$("html").unbind("mouseleave");
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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">
Are you sure you want to navigate away from this page?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">No I want to stay</button>
<button id="okButton" type="button" class="btn btn-primary">Yes, I'm sure</button>
</div>
</div>
</div>
</div>