簡體   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