关于这个问题,js中有页面关闭的页面关闭beforeunload事件,该事件的主要弊端是不能对弹出框进行自定义。现如今主要造成这种局面的原因是浏览器的本身操作(如前进,后退,刷新)无法仅仅通过前端进行控制。下面介绍一种HTML5的方法阻止页面的前进后退(不包括刷新,这个需要继续推敲下)。
if (window.history && window.history.pushState) {
$(window).on('popstate', function () {
window.history.pushState('forward', null, '#');
window.history.forward(1);
});
}
window.history.pushState('forward', null, '#');
window.history.forward(1);
<div class="confirm_win">
<h2>您输入的内容尚未保存,确定离开此页面吗?</h2>
<div class="confirm_win_btn">
<a href="javascript:;" class="yes">确认</a>
<a href="javascript:;" class="no">取消</a>
</div>
</div>
.confirm_win{
width: 400px;
height: auto;
padding: 20px 30px;
background: #fff;
position: fixed;
left: 50%;
top: 50%;
margin-top: -110px;
margin-left: -200px;
z-index: 10000;
overflow: hidden;
font-size: 14px;
display:none;s
}
.confirm_win h2{
line-height: 40px;
text-align:center;
width: 100%;
float: left;
height: 40px;
font-size: 16px;
color: #333;
margin-bottom:13px;
margin-left:-5px;
}
.confirm_win .confirm_win_btn a{
float:right;
margin-right:40px;
color:#2196f3;
}