【问题标题】:How to make forward button work on this example using HTML5 history?如何使用 HTML5 历史记录在此示例中使用前进按钮?
【发布时间】:2015-02-25 18:36:25
【问题描述】:

在这个例子中,我们设法使后退按钮工作,但前进按钮似乎是一个问题,当按下前进按钮时,#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>

Here is JSBin

谢谢!

【问题讨论】:

  • 什么是 history.pushState(null, null, null);正在做?我看不到后退按钮或前进按钮。从代码中不清楚你在做什么。

标签: javascript jquery html html5-history


【解决方案1】:

通过将所有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 });
});

» demo

【讨论】:

    【解决方案2】:

    你可以用“hash”代替“history”

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

    这是demo

    【讨论】:

      猜你喜欢
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      相关资源
      最近更新 更多