【发布时间】:2016-10-28 23:37:46
【问题描述】:
我只想使用引导程序 3 创建一个模式页面,该页面的行为与按下浏览器后退按钮或模式内的关闭按钮相同。我找到了一个可以执行此操作的脚本,但是有一个问题。假设我从 google.com 开始,进入这个模态页面,然后按下“模态!”按钮,然后按浏览器后退按钮,它将关闭模式,如果我再次按后退按钮,它将带我回到 google.com(一切都很好)。但是这一次,如果我打开模式页面并使用“关闭”按钮关闭模式。但现在,我必须按两次后退按钮才能返回 google.com。如果我使用模态内部的关闭按钮打开和关闭模态 10 倍。我发现我必须再按 10 次浏览器返回按钮才能返回 google.com 页面。如何解决这个问题? TIA
<!--html, bootstrap 3.2.0-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<p>If you press the web browser's back button not the modal's "close" button, the modal will close and the hash "#myModal" will be removed for the URL</p>
</div>
<div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div>
</div>
</div>
</div>
<!--jquery-->
$('#myModal').on('show.bs.modal', function (e) {
window.history.pushState('forward', null, '#modal');
});
$('#myModal').on('hide.bs.modal', function (e) {
//pop the forward state to go back to original state before pushing the "Modal!" button
});
$(window).on('popstate', function () {
$('#myModal').modal('hide');
});
【问题讨论】:
-
你在模态隐藏事件中尝试过
window.history.back();吗? -
我试过了,它没有关闭模式,而是完全访问 google.com。
-
我认为发生这种情况是因为当您关闭模态时,
window.history.back();会触发一个弹出状态,这会触发模态再次关闭,从而触发另一个window.history.back() -
所以,它开始了。也许,在某些条件下使用它可以带来你的结果。尝试调试历史记录。你也可以看看这里:html5doctor.com/history-api
-
感谢您的所有评论,这些评论澄清了正在发生的事情。这花了一些时间,但帮助我得出了我的解决方案。谢谢!
标签: jquery bootstrap-modal browser-history