Close pop up on back button

后端 未结 10 1537
长发绾君心
长发绾君心 2020-12-08 08:15

I want to close pop up on click of back button for mobile. I implemented this using onhashchange:

window.onhashchange = function (event) {

};
10条回答
  •  误落风尘
    2020-12-08 08:28

    This is my solution for bootstrap modals. It adds support closing with back button to all bootstrap modals. You can adapt it for your non-bootstrap popups.

    //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');
            }
        });
    })();
    

提交回复
热议问题