【问题标题】:How to use the browser history api to invoke a function when back & forward buttons are clicked?单击后退和前进按钮时如何使用浏览器历史记录 API 调用函数?
【发布时间】:2014-07-25 18:49:10
【问题描述】:

假设我有一个页面:http://www.example.com/foo.htm

我想放置一个按钮来显示页面的一部分并隐藏另一部分,例如:

HTML-

<p class="stepOne">Hi, I'm step one. <a id="doit" href="#">Go to Step 2</a></p>
<p class="stepTwo">And I'm step two</p>

JS-

$('#doit').on('click', function(){
    $('.stepOne').hide();
    $('.stepTwo').show();
});

我的问题是: 用户点击“Go to Step 2”链接后,当用户点击浏览器的返回按钮时,如何使用HTML history api隐藏第二步并显示第一步?

【问题讨论】:

  • 这通常是通过 popstate 事件完成的,但是在使用 history api 做任何事情时请记住浏览器支持。我倾向于使用库而不是自己构建它,因为如果您想要与常见但不太现代的浏览器兼容,它会非常复杂。
  • 使用一些棘手的 css,你实际上可以在没有 javascript 的情况下完成它。 jsfiddle.net/Ps4XW :) 适用于现代浏览器。

标签: javascript browser-history history.js


【解决方案1】:

让我们将浏览器的历史视为一个堆栈。每次单击链接或向前导航时,都会将项目推入堆栈。每当您想后退时,浏览器都会从堆栈中“弹出”一个项目。让我们将这些项目中的每一个称为“状态”。浏览器会保留一些关于每个状态的信息,如 URL、标题和“状态对象”(如果需要)。总而言之,当您前进时,新状态会被推送到堆栈中,而当您想要后退时,最新状态会从末尾弹出。

考虑到这一点,您想要完成的是手动将状态压入堆栈。通过这种方式,用户实际上并没有在任何地方导航——HTML5 History API 让我们能够在不改变页面的情况下推送/弹出/替换浏览器历史堆栈中的状态。

在您的click 事件侦听器中,您需要添加一些代码以将新状态添加到历史堆栈。比如:window.history.pushState({}, 'Step 2', '/step-2');

这将向历史堆栈添加一个新状态,并且您的 URL 将更改为 /step-2。现在,当您单击后退按钮时,它将pop 此状态脱离堆栈并返回到先前的状态。两种状态都是相同的页面和 DOM。

现在,当用户在浏览器中导航back 时,您必须考虑更改页面上这两个项目的可见性。这可以通过popstate 事件检测到,每次状态更改时都会在window 上触发该事件。看看我整理的this plunkr example。在单击事件侦听器中,DOM 被更改(隐藏和显示项目),并且新的历史状态被推送到堆栈中,其中一个整数表示应该在该历史状态中显示哪个步骤。然后,在popstate 事件中,用户正在向后导航,在事件对象中,我们得到了正在弹出的状态。我们知道我们应该倒退,所以如果弹出的步骤是第 2 步,我们将要显示第 1 步。

我对 html 做了一些小改动,以便能够简洁地编写代码,并且这里有很大的模块化空间 - 无需在 javascript 中硬编码步骤编号。

这有意义吗?

【讨论】:

    【解决方案2】:

    以下代码响应解决您在问题中提出的问题。使用HTML5 History Api,我们像这样扩展您的示例代码(cmets 描述已添加到您的代码中的三个部分 A、B、C)

    // Part A: For the initial "step 1" we create a history state object
    var historyStateObjectStep1 = {"step":"one"};
    // which we tell the browser to use to represent the current state/step in
    // history. Since the browser had an idea about the "now"-state in history 
    // already, which is now "replaced" this is done via history.replaceState
    history.replaceState(historyStateObjectStep1,"");
    
    // Part B: To react to history events like back-/forward-button pressed, 
    // we have to setup an EventListener for the "history"-popstate event. 
    window.addEventListener("popstate",function(event){
          // the history state objects we have setup via replaceState/pushState
          // before are provided via the event objects property event.state
          var historyStateObject = event.state;
    
          // if state object is "object" and as setup has an attribute "step" 
          // with value "one"
          if(typeof historyStateObject == "object" 
             && historyStateObject.step === "one" )
          {
              // then it means that the user used the browsers "back" button 
              // and since we are now at history state "stepOne" we show it
              $('.stepOne').show();
              // and hide stepTwo
              $('.stepTwo').hide();
          } 
          // in else case that the historyStateObject is an object and has an
          // attribute step set to the value "two" then...
          else if(typeof historyStateObject == "object" 
             && historyStateObject.step === "two" )
          {
              //...the user has used the browser buttons (forward/back) to reach
              // the state "stepTwo", hence we show it and 
              $('.stepTwo').show();
              // hide stepOne
              $('.stepOne').hide();
          }
    },false);
    
    
    $('#doit').on('click', function(){
        // PART C: Upon clicking the "doit"-button (to go to step two), we 
        // create an history state object for step 2 
        var historyStateObjectStep2 = {"step":"two"};
    
        // which we then insert intto the browser history, or in other words 
        // "push" the newly created historyStateObejectStep2 to the history, via
        // the function history.pushState
        history.pushState(historyStateObjectStep2,"");
    
    
        $('.stepOne').hide();
        $('.stepTwo').show();
    });
    

    【讨论】:

      猜你喜欢
      • 2014-03-21
      • 1970-01-01
      • 2015-05-18
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多