繁体   English   中英

关闭后退按钮弹出

[英]Close pop up on back button

我想在单击移动设备的后退按钮时关闭弹出窗口。 我使用 onhashchange 实现了这个:

window.onhashchange = function (event) {

};

在这种情况下,如果弹出窗口多次打开,然后单击后退按钮,它会打开和关闭模式弹出窗口。 但是,我希望模态弹出窗口在第一次返回时关闭并导航到下一次返回的上一页。

我也尝试使用 onbeforeunload,但它会显示另一个离开或留在页面上的警报。

$(window).bind('beforeunload', function(e) {
    return false;
});

关闭后退按钮弹出并重定向到下一个页面的上一页的最佳方法是什么?

当我测试我的答案时,bootply.com 已关闭。 请参阅下面代码底部的内联脚本和注释。 其余的只是 Twitter Bootstrap 样板,以便我可以轻松地在本地测试它。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>modal.html</title>
    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <p>If you press the back button now, you should return to whatever page you were on before this page.</p>
    <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Show me the modal!</button>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
            <p>If you press the web browser's back button OR the modal's close buttons, the modal will close and the hash will return to "modal.html#modalClosed".</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

    <script type="text/javascript">
      // Immutable hash state identifiers. 
      var closedModalHashStateId = "#modalClosed";
      var openModalHashStateId = "#modalOpen";

      /* Updating the hash state creates a new entry
       * in the web browser's history. The latest entry in the web browser's
       * history is "modal.html#modalClosed". */
      window.location.hash = closedModalHashStateId;

      /* The latest entry in the web browser's history is now "modal.html#modalOpen".
       * The entry before this is "modal.html#modalClosed". */
      $('#myModal').on('show.bs.modal', function(e) {
        window.location.hash = openModalHashStateId;
      });  

      /* When the user closes the modal using the Twitter Bootstrap UI, 
       * we just return to the previous entry in the web 
       * browser's history, which is "modal.html#modalClosed". This is the same thing
       * that happens when the user clicks the web browser's back button. */
      $('#myModal').on('hide.bs.modal', function(e) {
        window.history.back();
      });      
    </script>
  </body>
</html>
if (window.history && window.history.pushState) {
    $('#myModal').on('show.bs.modal', function (e) {
        window.history.pushState('forward', null, './#modal');
    });

    $(window).on('popstate', function () {
        $('#myModal').modal('hide');
    });
}

这可以使用Apache Cordova轻松完成,但不确定您是否使用它在 webview 中显示您的页面。

function onBackKeyDown(e) {
  e.preventDefault();

}
document.addEventListener("backbutton", onBackKeyDown, false);

http://cordova.apache.org/docs/en/2.4.0/cordova_events_events.md.html#backbutton

根据http://www.mylearning.in/2015/06/close-modal-pop-up-on-back-button.html

    $('#myModal').on('show.bs.modal', function(e) {
        window.location.hash = "modal";
    });

    $(window).on('hashchange', function (event) {
        if(window.location.hash != "#modal") {
            $('#myModal').modal('hide');
        }
    });

这是我对 bootstrap modals 的解决方案。 它为所有引导模式添加了使用后退按钮关闭的支持。 您可以针对非引导弹出窗口进行调整。

//Modal Closer With Back Button Support (Uses EventDelegation, so it works for ajax loaded content too.)
(function() {
    var activeOpenedModalId     = null;
    var isHidingModalByPopState = false;
    $(document).on('show.bs.modal', '.modal', function() {
        activeOpenedModalId  = $(this).attr('id');
        window.location.hash = activeOpenedModalId;
    }).on('hide.bs.modal', '.modal', function() {
        if(!isHidingModalByPopState) {
            window.history.back();
        }
        isHidingModalByPopState = false;
        activeOpenedModalId     = null;
    });
    $(window).on('popstate', function() {
        if(activeOpenedModalId && window.location.hash !== '#'+activeOpenedModalId) {
            isHidingModalByPopState = true;
            $("#" + activeOpenedModalId).modal('hide');
        }
    });
})();

通过单击返回,自动激活$('.modal').hide()函数。 所以不需要隐藏模态。 我们可以在后退按钮后看到灰色阴影背景。您可以使用这些代码行中的任何一行来关闭模态弹出窗口。

  1. $('.modal').modal('隐藏').data('bs.modal', null); [在引导程序 3 上工作]

或者

  1. $('body').removeClass('modal-open');

    $('.modal-backdrop').remove();

当模态处于活动状态时检查页面,您可以看到这些类。 如果此方法错误或存在其他简单方法,请纠正我。

我为我自己的网站编写了这段代码

并在不同的设备和浏览器上测试了太多次

Chromium 71Chrome 67FireFox 65Android 4.1Android 4.2Android 7.1

window.onload=function(){

    State=0;

    $(".modal").on("show.bs.modal",function(){
        path=window.location.pathname+window.location.search;
        history.pushState("hide",null,path);
        history.pushState("show",null,path);
        State="show";
    })
    .on("hidden.bs.modal",function(){
        if(!!State)
            history.go(State=="hide"?-1:-2);
    });

    setTimeout(function(){// fix old webkit bug
        window.onpopstate=function(e){
            State=e.state;
            if(e.state=="hide"){
                $(".modal").modal("hide");
            }
        };
    },999);

    $("#myModal").modal("show");
};
  • 不要使用$(document).ready而不是window.onload

我的 Angular 解决方案

// push history state when a dialog is opened
dialogRef.afterOpened.subscribe((ref: MatDialogRef<any, any>) => {
  window.history.pushState(ref.id, '');
  // pop from history if dialog has not been closed with back button, and gurrent state is still ref.id
  ref.afterClosed().subscribe(() => {
    if (history.state === ref.id) {
      window.history.go(-1);
    }
  });
});

问题:当模态打开并且用户单击浏览器的后退按钮时,页面导航(向后或向前)但模态保持打开状态。

解决方案 :

在 JavaScript 中:

$(window).on('popstate', function() {
  $('.modal').click();     
});

在角度:

  ngAfterViewInit() {
$(window).on('popstate', function() {
  $('.modal').click();     
});}

只需将此代码添加到脚本中:

//update url to current url + #modal-open. example: https://your-url.test/home#modal-open
$('body').on('shown.bs.modal', '.modal', function () {
   location.hash = '#modal-open'
})

//remove #modal-open from current url, so the url back to: https://yoururl.test/home
$('body').on('hidden.bs.modal', '.modal', function () {
   location.hash = ''
})

//when user press back button
$(window).on('hashchange', function (e) {
   if(location.hash == ''){
      $('.modal').modal('hide')
   }
})

即使模态被多次打开和关闭,上面的代码也能完美运行。

*注意:jQuery 3.^ Bootstrap 4.^

我不喜欢 hash。 此代码在 url 中没有 hash

  onModalMounted() => {
    if (isMobile) {
      history.pushState('modalShow', "", path); // add history point
      window.onpopstate = (e) => {
        e.stopPropagation()
        e.preventDefault()
        closeModalFn() // your func close modal
        history.replaceState('', "", path);
        window.onpopstate = () => {} // stop event listener window.onpopstate
      }
    } else {
      window.onpopstate = (e) => {
        e.stopPropagation()
        e.preventDefault()
        closeModalFn() // your func close modal
        window.onpopstate = () => {} // stop event listener window.onpopstate
      }
    }
  }

我会这样做:

// 2.0 and above
@Override
public void onBackPressed(evt) {
    evt.preventDefault();
    closeTab();
}

// Before 2.0
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        evt.preventDefault();
        closeTab();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

--> 顺便说一句,这些是处理程序,需要 addEventListener =)

我是凭记忆完成的,稍后我会在“代码混乱”文件夹中找到它时进行检查

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM