bootstrap 3关闭模式按下浏览器后退按钮

问题描述 投票:5回答:3

我只是想创建一个模态页面,其行为相同,要么使用bootstrap 3按下浏览器后退按钮或模式内的关闭按钮。我找到了一个脚本来执行此操作,但是存在问题。让我说我开始使用google.com,转到这个模态页面,然后推送“模态!”按钮,然后按下浏览器后退按钮,它将关闭模式,如果我再次按下后退按钮,它将带我回google.com(一切都很好)。但这一次,如果我打开模态页面并使用“关闭”按钮关闭模态。但现在,我必须按两次后退按钮才能返回google.com。如果我用模态内的关闭按钮打开和关闭模态,如10x。我发现我必须再次按下浏览器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');
});

jsfiddle source

jquery bootstrap-modal browser-history
3个回答
2
投票

您可以使用以下代码来摆脱打开的模态窗口,而不是意外地移动到浏览器的上一页。

//When ever the modal is shown the below code will execute.
$(".modal").on("shown.bs.modal", function()  {
    var urlReplace = "#" + $(this).attr('id'); 
    history.pushState(null, null, urlReplace); 
  });

  // This code gets executed when the back button is clicked, hide any/open modals.
  $(window).on('popstate', function() { 
    $(".modal").modal('hide');
  });

0
投票

我找到了解决方案。随意发布任何其他优雅的解决方案。

$('#myModal').on('hide.bs.modal', function (e) {
    if(location.hash=='#modal')window.history.back();
});

$(window).on('popstate', function (event) {  //pressed back button
    if(event.state!==null)$('.modal').modal('hide');
});

0
投票

在按钮上单击弹出窗口将出现。

$(document).ready(function(){
      $(".popup-btn").click(function () {
          location.hash = "popup";
          $(".popup-panel").show();
      });
});

在位置更改时,它将被隐藏:

$(window).bind('hashchange', function () {
      if (location.hash == null || location.hash == "") {
          $(".popup-panel").hide();
      }
});
© www.soinside.com 2019 - 2024. All rights reserved.