HTML5 HistoryAPI

          HTML5规范中,history对象提供了丰富的接口使得开发者可以方便的在历史记录中添加状态或改变状态,这样我们既可以使用javascript更新页面,又能更新地址栏和浏览器记录。

      

         以前的解决方案

         1、window.history.back(): 后退到上一个页面

         2、window.history.forward():前进到下一个页面

         3、window.history.go():跳转到某一个页面,go(0)代表刷新当前页面,go(-1)代表跳转到前一个页面,诸如此类

         4、window.history.length:当前页面历史记录的条数

 

 

         现在的解决方案

         提供了两个新方法:pushState() 和 replaceState(),它允许我们添加和改变当前的浏览器地址。pushState用于向history对象添加当前页面的记录,并且改变浏览器地址栏的url,有三个参数,分别是state对象(一个javascript对象记录要插入到历史记录条目的相关信息)、标题、可选参数目标URL。

pushState(data, title ,[ url])。url不写时表示当前页面。实例代码如下:

history.pushState({username: "html5"}, "user account", "user.html");

         attention: pushState()带来地址栏变化不会触发hash跳转。

 

         replaceState()类似于pushState(), 只是将当前页面的历史记录。参数这些与pushuState()一样。

         另外HTML5还提供了onpopstate事件,该事件在窗口历史记录改变时被触发。示例代码:

window.onpopstate = function(event){
    console.log(event.state);//输出pushState()或replaceState()设置的state状态
}

         下面将演示一个简单的例子,用javascript更新页面内容时通过History API 来改变页面地址和历史记录。

 

<div id="click-item"></div>
<div id="result-item"></div>

<script>
   
var clickItem = document.getElementById('click-item');
   
var resultItem = document.getElementById('result-item');
   clickItem.onclick 
= function(){

       resultItem.innerHTML 
= 'clicked';
       history.pushState({note : 
"set result"} ,'' ,'result.html');
   }
</script>

单击click-item元素时,浏览器页面地址变为result.html,同时浏览器的历史记录也出现此页面的访问记录。

posted on 2012-09-16 15:41  小海少  阅读(322)  评论(0编辑  收藏  举报