簡體   English   中英

如何使用HTML5歷史記錄使前進按鈕在此示例上起作用?

[英]How to make forward button work on this example using HTML5 history?

在此示例中,我們設法使后退按鈕起作用,但前進按鈕似乎是一個問題,當按下前進按鈕時, #modal應該重新出現,但沒有出現。 有解決的辦法嗎?

 $(window).bind('popstate', function() { $('#modal').hide(); }); $(".view").click(function() { history.pushState(null, null, null); $("#modal").show(); }); 
 #modal { position: relative; display: none; height: 100px; width: 100px; background-color: grey } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button class="view">Click</button> <div id="modal"></div> 

這是JSBin

謝謝!

您可以使用“哈希”代替“歷史記錄”

$(window).bind('popstate', function() {
  if(location.hash.indexOf('#modal') != -1)
      $('#modal').show();
  else
    $('#modal').hide();
});

$(".view").click(function(){
  location.hash ='#modal';
  $("#modal").show();
});

這是一個演示

通過將所有null推入歷史記錄,您不會以任何方式耦合頁面的狀態/視圖。 您是否知道當您沿着堆棧前進時也會觸發popstate事件?

大多數人傾向於使用稱為“路由”的相對URL(或片段)來解析歷史記錄/內容,但您也可以使用pushState的第一個參數添加數據-大規模管理此機制的方式超出了范圍,但一個簡單的例子如下:

$(window).bind('popstate', function() {
    var state = history.state || {};
    state.openModal ? $('#modal').show() : $('#modal').hide();
});

$(".view").click(function(){
    $('#modal').show();
    history.pushState({ openModal: true });
});

»演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM